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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度