1

可能重复:
如何在 MySQL 插入语句中包含 PHP 变量

我想按名称选择 Wordpress 类别的类别 ID。奇怪的是,如果我手动定义类别,它一切正常。

echo 命令给了我类别名称,最后我在变量 $catid 中获得类别 ID。

但是,如果我通过表单发送它,则 echo 命令会为我提供与手动定义时完全相同的类别名称,但 MySQL-Command 不起作用,这意味着 $catid 变量保持为空。

这里有没有人有一个想法,因为我无法理解为什么它在直接定义时有效,但在通过表单发布完全相同的字符串时无效。下面的代码示例是我的代码的一部分,其中 $category 变量通过表单传递。如果我要取消注释手动变量并注释 post 变量,它将全部工作。

// $category = "Manual"; // manually defined

$category = $_POST['category']; //defined through a form

echo $category;

$connect = mysql_connect(localhost,abc,def); 

if (!$connect) {
    die('Could not connect: '.mysql_error());
}

mysql_select_db("abc");
$queryresult = mysql_query("SELECT * FROM `wp_terms` WHERE `name`='$category' LIMIT 0,1");

while($row = mysql_fetch_array( $queryresult )) {
     $catid = $row[term_id];
}
4

1 回答 1

0

It's a good idea to confirm the contents of your post data, something like this:

print_r($_POST); die;

That will allow you to see if your variable is even present in the submission, my bet is either you aren't passing it, or it's coming through under another name (Maybe even a typo).

It's difficult to answer this question without the form and the processing code, but you can at-least de-bug your data, by dumping variable contents to screen.

Hope this helps.

PS: This is wasting resources:

echo "$category";

You can use this:

echo $category;

PPS: Best to clean your variables to prevent SQL injection, this code is very dangerous:

$category = $_POST['category'];
mysql_query("SELECT * FROM `wp_terms` WHERE `name`='$category' LIMIT 0 , 1");

If your variable is passing from PPOST correctly, try de-bugging your SQL query like so:

$query = sprintf("SELECT * FROM wp_terms WHERE name='%s' LIMIT 0,1", $category);
print_r($query); die;

Then if you have some interface for your database running, try throwing your query through it and checking for errors and results (Just to confirm your retrieval statement).

If this works fine, then you know it's something to do with your SQL connect statements for sure, and you'll need to find your PHP version and dump out the value of $connect. Are you running this code on a shared hosting environment, or your own private server?

于 2013-01-06T14:51:48.103 回答