2011-02-15 60 views
0

它必須是最簡單的錯誤,但我沒有看到也沒有找到它。我的插入語句(php到mysql)無法使用我的變量

我使用值7填充變量$aa_minerid。 我在插入中使用此變量。 插入總是插入數據庫中的一個0(零)從未有7

我把它放在該字段是一個smallint(6) 我試圖

VALUES ('$aa_productid') 
VALUES ($aa_productid) 
VALUES ("$aa_productid") 
VALUES ('{$aa_productid}') 
VALUES ("{$aa_productid}") 

和所有與使用`藏漢 到腳本放在此後。

如果我放在那裏:VALUES (7) 它確實工作。

那麼我在這個腳本中做了什麼錯? BTW末回波就顯示變量$ aa_productid權值

<?php 

/* This php script should transfer data from the aa to the sql database */ 

// Info coming from aa 

$aa_productid = 7 ; 

include ("dogs.inc"); 

$cxn=mysqli_connect($host,$user,$passwd,$dbname); 

$query = 'SELECT * FROM `Price` WHERE ' 
     . ' `Time_Stamp`=(select max(`Time_Stamp`) from `Price` where `Product_ID` = \'1\')'; 

$result=mysqli_query($cxn,$query) or 
       die("Couldn't execute select query"); 

$row = mysqli_fetch_row($result); 

$aa_price=$row[3] ; 

$aa_value = $aa_price * $aa_amount; 

// Info ready to go to database 

$sqlinsert = 'INSERT INTO Mining (Product_ID)' 
     . ' VALUES ($aa_productid)' ; 

echo $aa_productid; 
+0

你記得在最後使用$ sqlinsert運行mysqli_query,對嗎? – 2011-02-15 18:24:43

回答

0

嘗試根據用於beging字符串撇號的類型 '.$aa_productid.'".$aa_productid."

,使用相同的一。

此外,如果您正在使用",那麼你應該能夠只是做

$insert="INSERT INTO $tablename;";

3

單引號不要做PHP變量擴展。但我會建議你使用準備好的語句,如:

$stmt = $cxn->prepare('INSERT INTO Mining (Product_ID) VALUES (?)'); 
$stmt->bind_param('i', $aa_productid); 
$stmt->execute(); 

參見文檔在preparebind_param

這將保護你免受SQL injection

0

這已經有一段時間,因爲我做任何PHP但..

我認爲你需要有smartquotes開啓

試試這個:

$sqlinsert = 'INSERT INTO Mining (Product_ID)' 
    . ' VALUES ('. $aa_productid .')' ; 

串聯可變進查詢。

0

當您在引號內使用變量時,如果您希望PHP解析其中的變量,則必須使用雙引號。所以,這會工作:

$sqlinsert = 'INSERT INTO Mining (Product_ID) VALUES ('.$aa_productid.')'; 

或者這會:

$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ($aa_productid)"; 
+0

mmmmm我非常專注於變量周圍的引號,並且從來沒有嘗試過改變整個語句中的單個和雙精度:)而且它的確有訣竅。你們真棒! – willie 2011-02-15 18:41:16

+0

一定要接受一個答案......他們中的任何一個都會做,因爲他們都是正確的。 :) – 2011-02-15 18:48:18

0

嘗試:

$查詢=「SELECT * FROM價格WHERE TIME_STAMP =(選擇價格其中,max(TIME_STAMP) Product_ID =「1」)「; ('$ aa_productid')「;其中,

另外,在將它們輸入到db之前,它總是一個好主意。

-1

試試這個語法來代替:

$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ("' . $aa_productid . '")"; 

無需串聯插入的兩個部分。也雙引號的變量似乎避免了問題。