开发者

When are variables evaluated in a mysql query?

I have a query:

$startdate= date('Y-m-d H开发者_开发问答:i:s',strtotime("-1 week"));

$query = "SELECT title FROM new_books ".
         "WHERE timestamp >= '$startdate' ";
$newbooks = mysql_query($query) or die (mysql_error());

Is the value of $startdate evaluated when $query is set, or when it's called by mysql_query()?

For example say the above query returns 0 results (mysql_num_rows($newbook)==0) could I change $startdate and then call $newbooks = mysql_query... again, or would I need to set $query again first?


The variable is evaluated at the time $query is set.

It's exactly like doing this:

$query = "SELECT title FROM new_books ".
         "WHERE timestamp >= '" . $startdate . "' ";

If you want to execute the same query multiple times with different parameters, use prepared statements:

$query = $mysqli->prepare("SELECT title FROM new_books WHERE timestamp >= :startdate");

$query->bind_params("s", $startdate);
$query->execute();
...

$query->bind_params("s", $an_other_startdate);
$query->execute();
...

See the examples at http://docs.php.net/manual/en/mysqli.prepare.php


Because it's encapsulated in double quotes, it will be evaluated when setting $query.


When you set a query like that, you are doing nothing but string concatenation as @arnaud576875 mentioned. You if you change the $startdate variable, you would need to reset the query.

You could potentially use sprintf like this before you pass it to mysql_query

$query_format = "SELECT title FROM new_books WHERE timestamp >= '%s'";
$newbooks = mysql_query(sprintf($query_format, $startdate)) or die (mysql_error());

Or just use prepared statements as suggested

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜