JonW
24 Nov 2009, 10:19 PM
I am trying to write a php script that searches for given information in a database and returns the result in a variable. I have created an image that better explains what I am trying to accomplish. I appreciate the help!
http://mantisclan.com/mysql.jpg
Alan
25 Nov 2009, 04:03 PM
Hmm looks like a phpBB3 table... So you want to pass in a username and return the associated user id?
Anyway, the following should work...
Assumptions:
the table name is 'user'
database details are already predefined in the following constants (DB_HOST, DB_USER, DB_PASS, DB_NAME)
function fetchUserID($username) {
// Establish a database connection
$db = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Clean the input so it's not malicious
$username = $db->real_escape_string($username);
// Construct the SQL query
$sql = "SELECT user_id FROM users WHERE username = '$username'";
// Execute the query in the database
$result = $db->query($sql);
// If there was only one result returned, grab the user_id and return it, otherwise return false
if($result->num_rows == 1) {
$dataArray = $result->fetch_assoc();
return $dataArray['user_id'];
}
return false;
}
$user_id = fetchUserID('Admin');
echo $user_id; // Should print out "2"
Powered by vBulletin® Version 4.2.0 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.