2011-02-15 61 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 . '")"; 

无需串联插入的两个部分。也双引号的变量似乎避免了问题。