簡體   English   中英

MySQL插入准備語句不起作用

[英]Mysql Insert prepared statement not working

我在第3張桌子中插入一些工作人員時遇到問題。

表首先包含first_id,test_name | 表秒包含second_id,test_second | 表的第一秒包含first_id,second_id,注釋 (可以為null)

$first_id = 1;
$second_id = 3;

$stmt = $this->conn->prepare("INSERT INTO first-second (first_id, second_id) values (?, ?)");
$stmt->bind_param("ii", $first_id, $second_id);
$result_insert = $stmt->execute();
$stmt->close();

在PHPMyadmin中,我可以執行插入操作,但是我不知道為什么使用stmt不起作用。

謝謝。

我會避免用破折號來定義表名,這不是一個好習慣。 無論如何,只要在表名之間插入反引號就可以解決您的問題。

像這樣:

"INSERT INTO `table-mame` WHERE ...

在表格名稱周圍添加反引號:

$stmt = $this->conn->prepare("INSERT INTO `first-second` (first_id, second_id) values (?, ?)");

但是建議不要在表名中使用“奇怪”字符。

我假設您正在使用文本框/文本區域或要求輸入以將數據插入數據庫的任何其他類型。 您的輸入中可能包含特殊字符,導致查詢失敗。 在插入查詢之前,嘗試使用mysqli_real_escape_string

$input1=mysqli_real_escape_string($_POST['input1']);
$input2=mysqli_real_escape_string($_POST['input2']);
$input3=mysqli_real_escape_string($_POST['input3']);

mysqli_query($conn,"INSERT INTO first-second (first_id, second_id, note) VALUES ('$input1','$input2','$input3')");

順便說一句,可以在表名中使用連字符,但不建議這樣做:
表格字段可以包含連字符嗎?

$first_id = 1;
$second_id = 3;

$stmt = $this->conn->prepare("INSERT INTO first-second (first_id, second_id) values (:f1, :f2)");
$result_insert = $stmt->execute(array('f1'=>$first_id , 'f2'=>$second_id));
$stmt->close();

希望能有所幫助。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM