【问题标题】:Error in an update mysql query execution with php and mysqli [duplicate]使用 php 和 mysqli 执行更新 mysql 查询时出错 [重复]
【发布时间】:2023-04-10 05:17:01
【问题描述】:

我正在尝试做一个小项目。我的任务是使用 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 {
    ?>

【问题讨论】:

标签: php mysql mysqli


【解决方案1】:

你需要使用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."'";

然而,你真的应该使用preparedstatements而不是连接字符串和转义字符,例如:

$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);

【讨论】:

  • 谢谢。这对我有用。我会将其标记为答案。我不能使用 PDO 或 Prepared statement,因为我的老师不会接受。我不知道为什么。但是非常感谢,先生。你就是男人。
  • 我的意思是,您甚至都没有错,但这确实不是我推荐给任何人的那种解决方案,甚至可能尤其是新开发人员。但也许这只是我。
  • 无事可做。现在请放下老师的事。我得到了我的答案。我的家庭作业完成了。 @Darshan Metha 非常感谢。
  • @all 我已对答案添加了更新并建议了推荐的方法。
猜你喜欢
  • 1970-01-01
  • 2019-06-20
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 2012-11-04
  • 2019-02-07
  • 1970-01-01
相关资源
最近更新 更多