0

I would like to get the id of an item in the database, set it to a variable, and use it. I'm quite new to all this coding stuff. I'm basing this on.

http://jameshamilton.eu/content/simple-php-shopping-cart-tutorial?PHPSESSID=99d373741727e3010a32319f1ebed001

cart.php?action=add&pdin=fbs

$product = $_GET[pdin];

I can't use an integer for 'pdin' so, id like to use its corresponding id which is an integer and plug it into this line of code which only takes integers?

$sql = sprintf("SELECT * FROM products WHERE pdin = %d;", $product);

so in i would take $product = 'pdin' find it's id $id = 'id' and plug it in to the above code

$sql = sprintf("SELECT * FROM products WHERE id = %d;", $id);

I tried reading up on this sql FROM SELECT WHERE... confused me some

4

3 回答 3

0

我会使用一个准备好的语句,这也会让你自己免受 SQL 注入的影响。你从 php 到 mysql 使用什么数据库接口?

这是一个选项:

$product = $_GET['pdin'];
$stmt = $db->Prepare("select * from products where pdin = ?");
$res = $db->GetAssoc($stmt,$product);
于 2013-05-13T22:18:04.790 回答
0

好的,我想通了。对不起,我昨晚没有解释清楚。我每天的脑电池有限,昨晚它耗尽了。

我想要的很简单。我想在数据库中找到与 id 相关的项目。

$query  = "SELECT * FROM products WHERE pdin = '$product'";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)) {
    $productID = $row['id'];
}

现在部分完成并返回正确的 id。并且“项目存在”功能正确触发。

//function to check if a product exists
function productExists($productID) {
    //use sprintf to make sure that $productID is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $productID); 

return mysql_num_rows(mysql_query($sql)) > 0;
}

所以,马克和米哈尔哈塔克;当您谈论在键上使用引号时,这是否意味着...

$sql = sprintf("SELECT * FROM products WHERE 'id' = %d;", $productID);

在“id”之类的东西周围加上引号?而且是为了安全?原谅我,我是一个新的平面设计师,不擅长代码。

于 2013-05-14T14:53:24.907 回答
0

顺便说一句,如果您通过键访问数组项,请始终使用引号('")否则 PHP(不必要)首先检查,如果键是常量

于 2013-05-13T22:23:11.660 回答