如何使用PHP从MySQL检索特定值? [英] How do I retrieve a specific value from MySQL with PHP?
问题描述
好吧,我真受够了.在过去的一周中,我将大部分空闲时间都花在了此事上.我知道查询在SQL中已更改,但我无法弄清楚.我可以找到的所有其他帖子似乎已经过时了.如果有人可以帮助我,我将非常感激.
Okay I'm so fed up. I've spent the better part of my free time for the past week trying to figure this out. I know that the query has changed in SQL but I cant figure it out. All of the other posts I can find seem to be outdated. If anyone could help me out I would really appreciate it.
我要做的就是通过使用唯一输入到数据库的唯一密码"来检索行的ID,然后将其设置为会话数据,以便可以在其他页面上使用该数据.我觉得这应该不难.
All I am trying to do is retrieve the id of a row by using a unique "passphrase" that I manually entered into a database and then set that as session data so that I can use that data on other pages. I feel like it shouldn't be this hard.
出于演示目的,这是我使用较旧的mysql_query的代码.
For demostration purposes here is my code using the older mysql_query.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'test321';
$db = 'local_test';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db); ?>
<?php
include 'includes/connection.php';
$pass = $_POST['inputPass'];
if(!$_POST['submit']) {
echo "please fill out the form";
header ('location: user_authenticate.php');
}
$query = "SELECT id FROM users WHERE pass= '$pass'";
$id = mysql_query($query);
$_SESSION["userId"] = "$id";
print $pass;
print $id;
print $_SESSION["userId"];?>
我尝试了很多事情,所以遇到很多不同的错误.我希望有人可以在这里指出正确的方向.最好的方法是什么?
I've tried a lot of things so I've gotten a lot of different errors. I am hoping someone could point me in the right direction here. What is the best way to do this?
推荐答案
首先,请不要使用mysql
API;已弃用,在PHP 7中不起作用.
First off, don't use the mysql
API; it's deprecated and won't work in PHP 7.
现在,这已经不合时宜了,mysql_query()
返回一个结果集资源(就像一个对象),其中可以包含多行,其中可以包含 >多列.要访问此资源的内容,必须将fetch
行插入数组,然后为所需列的索引进入该数组.您需要执行以下操作:
Now that that's out of the way, mysql_query()
returns a result set resource (which is like an object) which can contain multiple rows which can contain multiple columns. To access the contents of this resource, you have to fetch
a row into an array and then index into that array for the column you want. You need to do something like this:
$query = "SELECT id FROM users WHERE pass= '$pass'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
,然后您可以使用$id
的值.
and then you can use the value of $id
.
mysqli::query()
同样适用,它返回一个mysqli_result
对象.
The same holds for mysqli::query()
, which returns a mysqli_result
object.
这篇关于如何使用PHP从MySQL检索特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!