问题
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;
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.
回答1:
1) Don't use quotation in a field name or table name inside the query.
2) After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
It should work
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
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;
One note: please use mysqli_* or PDO since mysql_* deprecated.
回答2:
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO
is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
回答3:
You do this by using mysqli_fetch_field
method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field()
method as well, but it will be deprecated in php v5.5
回答4:
Try this
$value = mysql_result($result, 0);
回答5:
When you use mysql_fetch_object
, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field
instead of mysql_fetch_object
, that will give you the first field of the result set (id
in your case). The docs are here
回答6:
mysql_*
extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
PDO
The simpler option is PDO which has a neat helper function fetchColumn():
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
Proper PDO tutorial
MySQLi
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc()
could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
回答7:
It is quite evident that there is only a single id
corresponding to a single username
because username
is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
O/P
+----+
| id |
+----+
| id |
+----+
i.e. 'id'
actually is treated as a string not as the id
attribute.
Correct synatx:
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
Complete code
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
回答8:
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}
回答9:
This is a correct old version.
From documentation correct.
$sql2 = mysql_query("SELECT nombre FROM prov WHERE id_prov = '$array'");
$row2 = mysql_fetch_array($sql2);
$nombre = $row2['nombre'];
Have fun.
mysql_ (Old version)
mysqli_ (New version)
来源:https://stackoverflow.com/questions/59893254/get-id-from-mysql-database-and-load-data-based-on-it