将行插入mysql表失败

时间:2019-01-21 18:04:59

标签: php mysql

我已经尝试编写基于SELECT查询将字段插入数据库的代码。

以下是我的SELECT代码

<?php
    $sql = ("select * from category"); 
    $result = $con->query($sql); 
    if($result->num_rows > 0){
        while($row = $result->fetch_assoc()){
            $cat_id=$row['cat_id'];
            $cat_title=$row['cat_title'];
            echo "<option value=".$cat_id." >".$cat_title."</option>";
        }
    }
?>

这是我的插入脚本

$title = validateInput($_POST['title']);
$desc1 = validateInput($_POST['desc1']);
//$content = validateInput($_POST['content']);
$cat_title = validateInput($_POST['cat_title']);
$cat_id = validateInput($_POST['cat_id']);

$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?,?)"); 
$stmt->bind_param("sssssssssss", $title, $desc1,$category,$img, $img1,$img2,$img3,$zip, $user_id,$cat_title,$cat_id);
if($stmt->execute()){
     //echo "<script>alert('Your project added successfully');
     echo "<script>alert('Your project added successfully  ')</script>
<script>setTimeout(\"self.history.back();\",0000);</script>";
}else{
    echo "<script>alert('Failed added your project');</script>";
}

?>    

2 个答案:

答案 0 :(得分:0)

问题就在这里

$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?,?)"); 
$stmt->bind_param("sssssssssss", $title, $desc1,$category,$img, $img1,$img2,$img3,$zip, $user_id,$cat_title,$cat_id);

这是您的原始代码,问题是您插入产品$cat_title的位置应该在$desc1$category之间。

这应该有效:

$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title, img, img1,img2,img3,zip,user_id,cat_id) VALUES (?, ?, ?, ?,?,?,?,?,?,?)"); 
$stmt->bind_param("ssssssssii", $title, $desc1,$cat_title,$img, $img1,$img2,$img3,$zip, $user_id,$cat_id);

您也只有十列,但试图插入11列有价值的信息。

您必须将用户ID和Cat ID解析为整数而不是字符串。现在,此更新的代码应该可以使用了。您必须将参数与ssssssssii

绑定

答案 1 :(得分:0)

您要插入INSERT参数中缺少的参数,您指定11个字段,但仅输入10。用以下代码替换您的代码:

$title     = validateInput($_POST['title']);
$desc1     = validateInput($_POST['desc1']);
//$content = validateInput($_POST['content']);
$cat_title = validateInput($_POST['cat_title']);
$cat_id    = validateInput($_POST['cat_id']);

$stmt = $con->prepare("INSERT INTO products (title,desc1,cat_title,img,img1,img2,img3,zip,user_id,cat_id) VALUES (?,?,?,?,?,?,?,?,?,?)"); 
$stmt->bind_param("ssssssssss", $title,$desc1,$cat_title,$img, $img1,$img2,$img3,$zip,$user_id,$cat_id);
if($stmt->execute()){
    //echo "<script>alert('Your project added successfully');
    echo "<script>alert('Your project added successfully  ')</script>
    <script>setTimeout(\"self.history.back();\",0000);</script>";
} else {
    echo "<script>alert('Failed added your project');</script>";
}
?>