INSERT数据已成功,但未显示任何数据

时间:2017-01-09 06:26:17

标签: php mysql

我还没有发现我在编码中犯的错误。我尝试插入数据,代码显示没有错误,当我想查看数据时,它显示空白数据like this for example.如何解决此问题?

<?php
$connect = mysql_connect('localhost','root','');
$database = mysql_select_db('songdb');

$title = $_POST['title'];
$artist = $_POST['artist'];
$genre = $_POST['genre'];
$language = $_POST['language'];
$lyrics = $_POST['lyrics'];

$insert = "INSERT INTO `songs`(`title`,`artist`,`genre`,`language`,`lyrics`) VALUES('$title','$artist','$genre','$language','$lyrics')";

if(!mysql_query($insert)) {
    echo "Error." .mysql_error();
} else {
    header("Location: insert.php?msg=1");
}
?>

1 个答案:

答案 0 :(得分:0)

首先,您必须使用mysqli扩展名。因为不推荐使用mysql扩展名,所以必须使用预准备语句来防止sql注入。

 $connect = mysqli_connect('localhost','root','');
 mysqli_select_db($connect,'songdb');


    $title = $_POST['title'];
    $artist = $_POST['artist'];
    $genre = $_POST['genre'];
    $language = $_POST['language'];
    $lyrics = $_POST['lyrics'];

    //Preapared statement for inserting
    $insert = mysqli_prepare("INSERT INTO songs(title,artist,genre,language,lyrics) VALUES(?,?,?,?,?)");
    mysqli_stmt_bind_param($insert,'sssss', $title,$artist,$genre,$language,$lyrics);

if(!mysqli_stmt_execute($insert)){
echo "Error." .mysqli_error();
}
else { header("Location: insert.php?msg=1"); } ?>

有关详情,请参阅此处http://php.net/manual/en/mysqli.prepare.php