MySQL插入查询不起作用(PHP)

时间:2013-09-04 10:37:20

标签: php mysql sql insert

我需要帮助来理解为什么我的简单插入查询不起作用。

以下代码:

<?php

// db info
define ( 'DB_HOST', '' );`enter code here`
define ( 'DB_USER', '' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', '' );

create_db_connection ();
function create_db_connection() {
    global $con;

    $con = mysql_connect ( DB_HOST, DB_USER, DB_PASSWORD ) or die ( "connection not established" );
    $db = mysql_select_db ( DB_NAME, $con ) or die ( "database not connected" );
}


$sql= "insert into 'tbl_BonAproval' (OrderId,RestId) values (20001,98765)";


if (mysqli_query ( $db, $sql )) {
    echo "Successfully inserted " . mysqli_affected_rows ( $db ) . " row";
} else {
    echo "Error occurred: " . mysqli_error ( $db );
}
function close_mysql_connection() {
    global $con;
    mysql_close ( $con );
}

$result = mysql_query ( "SELECT * FROM `tbl_BonAproval`" );
$row = mysql_fetch_array ( $result );
print_r ( $row ); // print array
echo $row ['table field name']; // print field data

// $sql=mysql_query('INSERT INTO tbl_BonAproval (OrderId, RestId) VALUES (24553, 01001);');
                               // echo $sql;



mysql_close ( $conn );
class CallBack {
}

?>

3 个答案:

答案 0 :(得分:4)

您应该尝试 MySQLi ,而不是其前身 MySQL 。这是您的简化代码:

<?php

$conn=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

mysqli_query($conn,"INSERT INTO tbl_BonAproval (OrderId, RestId) VALUES ('20001','98765')");

$result = mysqli_query ($conn, "SELECT * FROM tbl_BonAproval");
while($row = mysqli_fetch_array ($result)){
echo $row['table field name']; /* print field data */ 
}

?>

答案 1 :(得分:2)

请勿混用mysqlmysqli。要使用mysqli,您应该打开mysqli连接。并在插入查询中使用表格名称的返回刻度。

EG:

$connection = mysqli_connect('HOST', 'USERNAME', 'PASS', 'TABLE'); //use mysqli connection

$sql= "insert into `tbl_BonAproval` (OrderId,RestId) values ('20001','98765')"; //for insert query

旁注:mysql_*已弃用,请使用mysqli_*PDO

答案 2 :(得分:1)

将插入查询更改为:

$sql= "insert into `tbl_BonAproval` (OrderId,RestId) values (20001,98765)";

您不能使用单引号来封装表名或列名。