使用变量来保存表名,并在查询中使用该变量

时间:2013-08-12 09:02:04

标签: php mysql string variables concatenation

我有下一个构造变量的代码:

 $idProvincia=$_GET["ciudad"];

表名将根据$ idProvincia值更改。 表名:

 $post="wp_".$idProvincia."_post";

我希望将$ post变量包含在查询中:

$result = mysql_query ("SELECT post.ID, post.post_title, post.guid, post.post_content, postmeta.meta_value, postmeta.meta_key
FROM `".$post."` AS post
INNER JOIN wp_".$idProvincia."_postmeta AS postmeta ON post.ID = postmeta.post_id
WHERE postmeta.meta_key='fc_start_datetime' AND post.post_status='publish' AND post.post_type='post'
ORDER BY postmeta.meta_value ") or die (mysql_error());

我无法得到正确的结果。我已经阅读了很多manuales但我无法使查询正常运行。

我想对更多变量执行相同的查询过程

1 个答案:

答案 0 :(得分:0)

您应该将该idProvincia内容移动到表body中,而不是名称。

将一个名为idProvincia的字段添加到表wp_post,然后以常规方式添加此编号:

$ciudad = mysql_real_escape_string($_GET["ciudad"]);
$sql = "SELECT post.ID, post.post_title, post.guid, post.post_content,
               postmeta.meta_value, postmeta.meta_key
FROM wp_post AS post
INNER JOIN wp_postmeta AS postmeta ON post.ID = postmeta.post_id
WHERE postmeta.meta_key='fc_start_datetime' AND post.post_status='publish' AND post.post_type='post' AND idProvincia = '$ciudad'
ORDER BY postmeta.meta_value "
$result = mysql_query ($sql) or trigger_error(mysql_error());
相关问题