繁体   English   中英

PHP从mysql数据库获取数据以获取查询字符串变量

[英]PHP getting data from mysql database for the Query string variable

这是我想做的; 我将经过编码的数据作为查询变量传递到我的网页,然后在我的php页面中,我对数据进行解码并在数据库中对其进行检查。 我正在使用的代码如下所示:

<?php
// Get the ID from URL.
$id = ( isset($_GET["id"]) && !empty($_GET["id"]) ? $_GET["id"] : "");

// If "id" is not empty, proceed.
if(!empty($id)) {
    $id = base64_decode($id);
    global $wpdb;
    $res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
    $tot = count($res);

    echo $tot . " records found.";

    for( $i=0; $i<count($res); $i++) {
        echo $res[$i]->id;
    }
    exit;
}
else {
    echo "No ID";
    exit;
}
?>

我的数据库中有一条记录。 上面的代码正确地说“找到1条记录”。 我不确定如何获取该行中字段的值。 我有3列,分别是id,field1和field2。 代码“ echo $res[$i]->id ”不返回任何内容。

请帮忙

顺便说一句,我正在我的Wordpress博客中尝试此操作。

谢谢大家的建议。 我尝试了您的建议,这是我的结果:

$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";

它说找到1条记录。

$res = $wpdb->get_row("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";

它说找到0条记录。

$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";  

它说找到0条记录。

while ($row = mysql_fetch_array($res)) {
echo $row[0];  
}

如果我使用mysql_fetch_array,

警告:mysql_fetch_array():在第38行的/home/myfolder/mytheme/index.php中提供的参数不是有效的MySQL结果资源。

第38行是while($ row = mysql_fetch_array($ res)){。

我要完成的工作:

我有一个wordpress博客。 上面所有的代码都进入了我的index.php。 我将通过查询字符串变量将产品ID传递给我的index.php。 我在我的wordpress数据库中创建了一个名为S_redirect的新表。 我将检索查询字符串变量id的值,并在数据库表中对其进行检查。 如果记录存在,则从该表行中检索列值之一(产品的网址),然后重定向到该产品的网址。 如果记录不存在,则重定向到主页。 希望这可以帮助每个人了解我在做什么。

$wpdb来看,这似乎是一个WordPress。 希望这会有所帮助: http : //codex.wordpress.org/Function_Reference/wpdb_Class


更新资料

不要使用count()来获取行数; 使用$wpdb->num_rows (no ()因为它是属性,而不是函数)。 对于任何无法识别为“可计数”值的非空值(即数组和某些对象), count()函数始终返回1,因此您的代码很可能始终产生1。

$tot = $wpdb->num_rows;

=====
如果使用get_results()而不是query()运行查询,则可以像这样循环遍历结果:

foreach ($res as $row) {
    echo $row->id;
}

最终,我认为您的代码最终将看起来像这样:

$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = $wpdb->num_rows;

echo $tot . " records found.";

foreach ($res as $row) {
    echo $row->id;
}

免责声明:这是未经测试的,因为我从未使用过WordPress。 这就是我从上面链接的文档中了解的方式。 希望它至少能使您走上正确的道路。

采用:

$tot = count(mysql_fetch_array($res));

要么

$tot = mysql_num_rows($res);

最好的是

while($ row = mysql_fetch_assoc($ res)){echo $ row ['column_name']; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM