[英]PHP not inserting array into MySQL database
我的php脚本没有将数组的内容插入MySql数据库中,这是一个代码片段。
<?php
session_start();
$host="localhost";
$user="root";
$password="";
$database="burudani db";
$con=mysqli_connect($host,$user,$password,$database);
if(!$con or !$database){
echo'Connection to MySQL failed!';
echo json_encode(0);
}else{
$datx=$_POST['data'];
if(isset($_POST['data'])){
$title=$datx[0];
$year=$datx[1];
$format=$datx[3];
$type=$datx[5];
$genre=$datx[6];
$desc=$datx[7];
$actors=$datx[11];
$imi=$datx[8];
$imr=$datx[9];
$pos=$datx[10];
$comments=$datx[2];
$price=$datx[4];
$sql="insert into `movies` values(NULL,'$title','$year','$format','$type','$genre','$desc','$actors','$imi','$imr','$pos','$comments','$price') or die(mysql_error());";
$result=mysqli_query($con,$sql);
if(!$result){
echo json_encode(1);
}
else{
echo json_encode(2);
}
}
else if(!isset($_POST['dat'])){
echo json_encode(3);
}
}
mysqli_close($con);
?>
数组$ datx是通过javascript通过ajax发送的。 现在,仅在数据库中存在title
情况下才插入记录。 例如,如果我尝试插入标题为“ Harry Potter”的记录,而数据库中没有标题为“ Harry Potter”的记录,则不会插入。 我尝试使用unset($datx);
但没有成功。 在MySQL中, title
字段的类型为text。 请帮忙,谢谢。
不要在mysql
和mysqli
之间mysqli
。
您也混合了查询和mysql错误功能
$sql="insert into `movies` values(NULL,'$title','$year','$format','$type','$genre','$desc','$actors','$imi','$imr','$pos','$comments','$price')";
// echo $ sql; 死; 在执行之前尝试打印和调试它
$result=mysqli_query($con,$sql) or die(mysqli_error($con));
您的SQL中有错误。 or die(mysql_error())
不属于那里。
我怀疑你是要写:
$sql="insert into `movies` values(NULL,'$title','$year','$format','$type','$genre','$desc','$actors','$imi','$imr','$pos','$comments','$price')";
$result=mysqli_query($con,$sql) or die(mysqli_error());
但是请注意,您的脚本容易受到SQL注入攻击的攻击
请仔细阅读准备好的声明 。 您的代码将变成这样:
// create a statement with placeholders for variables
$statement = mysqli_prepare($con, "insert into `movies` values(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
// bind the variables to the placeholders
// note: I do not know what datatypes you're expecting, so have assumed strings.
// modify the 'ssssssssssss' as required
mysqli_stmt_bind_param($statement, 'ssssssssssss', $title, $year, $format, $type, $genre, $desc, $actors, $imi, $imr, $pos, $comments, $price);
// execute the statement or show error (on production environment
// consider logging instead of displaying errors
mysqli_stmt_execute($statement) or die(mysqli_error());
// clean up the statement
mysqli_stmt_close($statement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.