【问题标题】:Build MySQL Query using a string INTO the Statement使用字符串 INTO 语句构建 MySQL 查询
【发布时间】:2013-11-14 16:07:32
【问题描述】:

我使用字符串构建了一个“INSERT INTO”MySQL 查询,但这个查询只更新了“date”列并返回“0”作为“id”列的值

$c= "2013-11-29 12:00:00";//whole code
$d= "2013-11-30 12:00:00";
$date_3 = date("Y-m-d g:i:s", strtotime("$c"));
$date_4 = date("Y-m-d g:i:s", strtotime("$d"));
$results = array($date_1);
$i = $date_3;
$allCane="";
while ($i <= $date_4) {
$i = date("Y-m-d g:i:s", strtotime($i));
array_push($results, $i);
$k= $i . "\n";
$chunks = str_split($k, 19);
$nexstring = join('\')', $chunks);
$cane = implode(', (\'{$id}\', \'', str_split($nexstring, 21));
$allCane .= $cane; // appends $cane to $allCane
$i = date("Y-m-d g:i:s",strtotime("+1 day", strtotime($i)));
}
$string ='(\'{$id}\', \' '.$allCane;
$string=substr($string,0,-12);
echo $string;//('{$id}', ' 2013-11-29 12:00:00'), ('{$id}', ' 2013-11-30 12:00:00')
$id=54;

$insert = mysql_query("INSERT INTO events (id, date) VALUES $string");
// i build the query using $string. 

$insert 的语法是正确的,但实际上我无法更新“id”列。

有什么方法可以使 $id 进入字符串?

【问题讨论】:

  • 请不要再使用mysql_* 函数,它们已被弃用。有关详细信息,请参阅Why shouldn't I use mysql_* functions in PHP?。相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is a good tutorial.
  • 你是如何创建你的$string的?
  • 在这种情况下,只需将 SQL 写入变量,而不是直接写入 mysql 命令。这样您就可以输出生成的查询并对其进行调试。调试就是一切!
  • 您的$string 中似乎包含文字字符串'$id'。这不会被$id 变量神奇地替换。你需要设置$id 之前你设置$string 然后添加$id 到它。
  • 或者需要使用str_replace将'$id'替换为$id的值。

标签: php mysql string


【解决方案1】:

包含在single quotes ('') 内的Variables 不会被解析,因此,在将变量名包含在字符串中时,请始终使用double quotes ("")。

在下面使用

$insert = mysql_query("INSERT INTO events (id, date) VALUES ('{$id}', ' 2013-11-29 12:00:00'), ('{$id}', ' 2013-11-30 12:00:00')");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    相关资源
    最近更新 更多