2016-03-01 148 views
1

我目前在學習PHP,並使用下面的查詢將值插入到我的MySQL表中。
我想檢查值是否正確插入。我曾嘗試編寫過一個IF語句,並通過大量例子進行了搜索,其中沒有一個看起來可行。檢查SQL INSERT是否成功

我將不勝感激任何幫助將我轉向正確的方向。

$dd_tracking_insert = $dd_tracking_conn->query("INSERT INTO $dd_tracking_table_name (invoice_id, user_id, gc_bill_id, gc_bill_amount, gc_bill_fees, gc_bill_status, gc_bill_created) VALUES ('$invoice_id', '$user_id', '$gc_transaction_id', '$invoice_amount', '$gc_fees', '$gc_status', now())"); 

如果插入正確 - echo "inserted"
如果錯誤:未插入 - echo "error: values where not inserted correctly."

鏈接到完整的代碼here

+0

Pdo rowcount是一種簡單的方法。增加插入循環並檢查表中最後的行數。 – cpugourou

+0

嘗試'mysql_affected_rows()'http://php.net/manual/tr/function.mysql-affected-rows.php –

+0

@mdemir OP使用'mysqli_'而不是'mysql_'。另外,如果您要參考PHP.net,請使用基於英文的。你的意思是http://php.net/manual/en/mysqli.affected-rows.php –

回答

0
if (!$dd_tracking_conn->query("INSERT...")){ 
    //echo "error: values where not inserted correctly."; 
    printf("Error: %s\n", $dd_tracking_conn->error); 
}else { 
    echo "inserted"; 
} 
3
  • 發佈這是一個社區的wiki。

要檢查您的INSERT是否成功,您可以使用mysqli_affected_rows()

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

面向對象的風格

int $mysqli->affected_rows;

程序風格

int mysqli_affected_rows (mysqli $link)

並檢查針對您的查詢和PHP錯誤。

參考:如果用戶的互動參與


你現在的代碼是開放的SQL injection。使用mysqli with prepared statementsPDO with prepared statements