douluolan9101 2017-12-18 22:17
浏览 53
已采纳

使用PHP将数据插入MySQL时出错[重复]

This question already has an answer here:

Strangest thing going on. I'm able to run this just fine in XAMPP. But when I move to my server which uses a socket to connect, it connects, but I can't insert. And I'm wondering if its due to a socket and I need to do things differently. I changed to = new mysqli as mysql_connect doesn't work with a socket. But outside of that, I'm a bit lost. When I run test.php I get

Error : ()

Test.PHP

    <?php
    $dbhost = "localhost";
    $socket = ":/diskID/mysql/socket";
    $dbname = "TUTORIALS";
    $dbusername = "root";
    $dbpassword = "password";

    $mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbname,$socket);

    //Output any connection error
    if ($mysqli->connect_error) {
       die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }

    $product_name = '"'.$mysqli->real_escape_string('P1234').'"';

    //MySqli Insert Query
    $insert_row = $mysqli->query("INSERT INTO tutorials_inf (name)VALUES($product_name)");

    if ($insert_row) {
        print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
    } else {
        die('Error : ('. $mysqli->errno .') '. $mysqli->error);
    }
</div>
  • 写回答

2条回答 默认 最新

  • doulou1989 2017-12-19 00:04
    关注

    When doing MySQL queries you should use single quote marks instead of quotation marks.

    Try using:

    <?php
    $dbhost = "localhost";
    $socket = ":/diskID/mysql/socket";
    $dbname = "TUTORIALS";
    $dbusername = "root";
    $dbpassword = "password";
    
    $mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbname,$socket);
    
    //Output any connection error
    if ($mysqli->connect_error) {
       die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }
    
    $product_name = "'".$mysqli->real_escape_string('P1234')."'";
    
    //MySqli Insert Query
    $insert_row = $mysqli->query("INSERT INTO tutorials_inf (name)VALUES(" . $product_name . ")");
    
    if ($insert_row) {
        print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
    } else {
        die('Error : ('. $mysqli->errno .') '. $mysqli->error);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决