用php和mysqli执行更新mysql查询时出错

时间:2019-04-03 13:00:41

标签: php mysql mysqli

我正在尝试做一个小项目。我的任务是使用HTML和PHP创建更新表单。但是我收到以下错误消息:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's standard dummy text ever since the 1500s, when an unknown printer.' , exp_time' at line 1

我将Laragon用于php,将HeidiSQL 9.5用于mysql服务器。

我的数据库连接正常。我可以使用同一文件中的SELECT查询从数据库中获取数据。我认为我的代码有问题。因此,请帮助我,代码如下:

    <?php
    require('auth.php');
    require('db.php');
    $id=$_REQUEST['id'];
    $query = "SELECT * FROM experience where expid='".$id."'";
    $result = mysqli_query($con,$query) or die ( mysqli_error($con));
    $row = mysqli_fetch_assoc($result);

    $status = "";
    if(isset($_POST['new']) && $_POST['new']==1)
    {


    $exp_title = $_REQUEST['exp_title'];
    $exp_description = $_REQUEST['exp_description'];
    $exp_time = $_REQUEST['exp_time'];
    $update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
    WHERE expid='".$id."'";
    mysqli_query($con, $update) or die ( mysqli_error($con));
    $status = "Record Updated Successfully. </br></br>
    <a href='dashboard.php'>View Updated Record</a>";
    echo '<p style="color:#FF0000;">'.$status.'</p>';
    }else {
    ?>

1 个答案:

答案 0 :(得分:-2)

您需要使用php的str_replace对单引号进行转义,例如:

$exp_title = str_replace("'", "\'", $_REQUEST['exp_title']);
$exp_description = str_replace("'", "\'", $_REQUEST['exp_description']);
$exp_time = $_REQUEST['exp_time'];
$update="UPDATE experience SET exp_title='".$exp_title."' , exp_description='".$exp_description."' , exp_time='".$exp_time."'
WHERE expid='".$id."'";

但是,您实际上应该真正使用PreparedStatement,而不是连接字符串和转义字符,例如:

$exp_title = $_REQUEST['exp_title'];
$exp_description = $_REQUEST['exp_description'];
$exp_time = $_REQUEST['exp_time'];
$stmt = $conn->prepare("UPDATE experience SET exp_title= ?, exp_description = ?, exp_time = ? WHERE expid = ?");
$stmt->bind_param("types", $exp_title, $exp_description, $exp_time, $id);