2017-02-03 21 views
1

我試圖插入兩個表,但得到這個錯誤PHP〜列數並不在行1匹配值數

Error: INSERT INTO provide_help (amount) VALUES (40,000.00) Column count doesn't match value count at row 1`

下面

是我的插入代碼

<?php 

    session_start(); { 



    //Include database connection details 
    include('../../dbconnect.php'); 


$amount = strip_tags($_POST['cat']); 
$field1amount = $_POST['cat']; 
$field2amount = $field1amount + ($field1amount*0.5); 



$sql = "INSERT INTO provide_help (amount) VALUES ($field1amount)"; 
if (mysqli_query($conn, $sql)) 


$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)"; 
if (mysqli_query($conn, $sql)) 

{ 
    $_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>"; 
    header("location: PH.php"); 
} else { 
    echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
} 

mysqli_close($conn); 
} 
?> 

但是當我做一些這樣的事它的工作原理

$sql = "INSERT INTO provide_help (amount) VALUES ($field2amount)"; 

我只是改變$field1amount$field2amount

,但我不希望它這樣,我想也得到$field1amount值並將其插入

請任何幫助將appriciated,感謝

+2

您可以[SQL注入](http://php.net/manual/en/security.database.sql-injection.php)和應該真正使用[Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)而不是連接你的查詢。特別是因爲你沒有逃避用戶輸入!這也可以解決你的逗號問題。 –

回答

9

的問題是因爲,您將在數有一個逗號,它不是一個字符串。您需要通過"40,000.00"40000.00。 MySQL將它解釋爲兩個值:40000.00

使用預準備語句將緩解此問題(以及您的安全問題),因爲綁定會將40,000.00解釋爲字符串。一個非常基本的例子,讓你開始將是:

$sql = "INSERT INTO provide_help (amount) VALUES (?)"; 
$stmt = $mysqli->prepare($sql); 

/* 
    - the "s" below means string 
    - NOTE you should still validate the $_POST value, 
     don't just accept whatever is sent through your form - 
     make sure it matches the format you're expecting at least 
     or you'll have data validation issues later on 
*/ 
$stmt->bindParam("s", $field1amount); 
$stmt->execute($fieldAmount1); 
$result = $res->fetch_assoc(); 
+0

我的建議實際上是儘可能使用PDO。請參閱http://php.net/manual/en/pdo.connections.php連接到數據庫和http://php.net/manual/en/pdo.prepared-statements.php來準備語句,綁定參數,並執行查詢。 – WOUNDEDStevenJones

相關問題