从MySQL数据库返回与特定PHP变量匹配的值?

时间:2014-01-03 18:54:12

标签: php mysql select where

我正在建立一个简单的待办事项网站,只是为了帮助我更好地学习mySQL。我在获取值返回时遇到了一些麻烦。当我使用“SELECT * FROM pages”作为我的查询时,所有数据都会恢复正常。 (页面是表名)

但是,我想要做的只是为一个特定用户提取一行数据。为了做到这一点,我在数据库中使用一个唯一的URL字段(以前用另一个函数创建)来选择返回数据的行。

我在这里缺少一些简单的东西,我希望有人可以找到我。使用以下代码,我得到一系列此错误,对应于我正在尝试输出的7个变量:(我知道SQL注入问题,这只是为了简单起见。另外,请原谅过度评论,我正在学习,这是我能跟上工作的唯一方式)

警告:mysql_result():提供的参数不是第16行/test/preview.php中的有效MySQL结果资源

<?php
include './includes/dbcon.php';

//declare $preview_url as the data submitted in the form under the 'preview_url' field
$preview_url = ($_POST['preview_url']);

//access db settings included in ./includes/dbcon.php
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

//select the row in the table that matches the passed variable from the form submission
$query="SELECT * FROM 'pages' WHERE 'url' = '".$preview_url."'";
$result=mysql_query($query);

// assign mySQL values from table to php variables
$email = mysql_result($result,1,'email');
$date=mysql_result($result,1,"date");
$title=mysql_result($result,1,"title");
$id=mysql_result($result,1,"id");
$items=mysql_result($result,1,"items");
$url=mysql_result($result,1,"url");
$expiry=mysql_result($result,1,"expiry");

//close the mySQL connection        
mysql_close();

?>

<html>
<head><title>Preview for <? echo $email; ?></title></head>
<body>
<strong>Email: </strong><a href="mailto:<? echo $email; ?>"><? echo $email; ?></a>        
<br />
<strong>Title: </strong><? echo $title; ?><br />
<strong>Date: </strong><? echo $date; ?><br />
<strong>Entry ID: </strong><? echo $id; ?><br />
<strong>Unique URL: </strong><a href="<? echo $url; ?>" target="_blank"><? echo          
$url; ?></a><br />
<strong>Link Expiration Date: </strong><? echo $expiry; ?><br />
<hr />
<strong>List:</strong><br />
<? echo $items; ?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

更改此代码部分Edwin

//select the row in the table that matches the passed variable from the form submission
$query="SELECT * FROM `pages` WHERE `url` = '".$preview_url."'";
$result=mysql_query($query);

if (!$result) {
    die(mysql_error());
}

// assign mySQL values from table to php variables
$email = mysql_result($result,1,'email');
$date=mysql_result($result,1,"date");
$title=mysql_result($result,1,"title");
$id=mysql_result($result,1,"id");
$items=mysql_result($result,1,"items");
$url=mysql_result($result,1,"url");
$expiry=mysql_result($result,1,"expiry");

//close the mySQL connection        
mysql_close();

另外,如果你真的很想学习,那么就知道mysql_函数已被弃用,很快就会消失。学习使用mysqli_功能和PDO。

http://us1.php.net/manual/en/book.mysqli.php

http://us1.php.net/manual/en/class.pdo.php