PHP和MySQL选择单个值 [英] PHP and MySQL Select a Single Value

查看:156
本文介绍了PHP和MySQL选择单个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这样一个基本的问题,但我没有找到一个简单的答案在任何地方。我想知道如何从我的mysql表中选择一个值。该表包括列username和id('id'是自动递增,'username'是唯一的)。给定用户名,我想设置一个会话变量 $ _ SESSION ['myid'] 等于对应于给定用户名的'id'列中的值。这里是我已经尝试过的代码:

Sorry for such a basic question, but I haven't found a simple answer anywhere. I'd like to know how to select a single value from my mysql table. The table includes columns 'username' and 'id' amongst others ('id' is auto-increment and 'username' is unique). Given the username, I want to set a session variable $_SESSION['myid'] equal to the value in the 'id' column that corresponds to the given username. Here's the code that I've already tried:

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;

到目前为止我得到了Catchable致命错误:stdClass类的对象无法转换为字符串。

So far I'm getting "Catchable fatal error: Object of class stdClass could not be converted to string." Casting $value to type string does not fix the problem.

推荐答案

$ value 1)不要在查询中的字段名或表名中使用引号。

1) Don't use quotation in a field name or table name inside query.

2)获取对象后,需要访问对象属性/属性)按属性/属性名称。

2) After fetching object you need to access object attributes/properties (in your case id ) by attributes/properties name.

应该可以工作

奖金提示:对此类型的问题使用限制1将节省执行时间:)

session_start();
$name = $_GET["username"];
$sql = "SELECT id FROM Users WHERE username='$name' limit 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value->id;

注意:请使用mysqli_ *或PDO,因为mysql_ *已弃用。

这篇关于PHP和MySQL选择单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆