I am an android/java developer and Im struggling with php.
I've made it as far as inserting a new user in the DB, now I want to get their ID.
What do I do with the result? I want to assign it to a variable.
$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";
$result =
PS: Im using mysql, not mysqli.
EDIT: Here is what I did:
$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email ."';";
$store_info = mysql_fetch_array(mysql_query($query));
$user_id = $store_info['user_id'];
$response["message"] = "User created with id: " . $user_id;
echo json_encode($response);
And the error message after inserting (successfully) the user in the db:
null{"success":3,"message":"User created with id: "}
I assume that your are using MySQLi API
$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query
$store_info = mysqli_fetch_array(mysqli_query($connection, $query));
//Execute the query, fetch the result, it's just one result so no need for a while loop
echo $store_info['user_id']; //echo id
As per the comments, you requested a mysql_() version so here you go...
$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query
$store_info = mysql_fetch_array(mysql_query($query));
//Execute the query, fetch the result, it's just one result so no need for a while loop
echo $store_info['user_id']; //echo id
Still consider using mysqli_() or PDO instead. Why? Because mysql_() is now deprecated, read the red box on the documentation page which says...
Refer this answer for PDO tutorial
Here is the PDO variant:
<?php
//credentials
$host = 'localhost';
$user = "user";
$password = '';
$db_name = 'test';
$port = 3306;
//connection to the database
try
{
$connection = new PDO("mysql:host=$host;port=$port;dbname=$db_name", $user, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
//prepare and execute SELECT statement
$sth = $connection->prepare("SELECT user_id FROM users WHERE user_email = :email");
$sth->execute(array(':email' => $user_email));
$record = $sth->fetch(PDO::FETCH_ASSOC);
print $record["user_id"];
If you use mysql (but you shouldn't, it's deprecated) :
$result = mysql_query("SELECT user_id FROM users WHERE user_email = '$user_email'");
$row = mysql_fetch_row($result);
echo $row[0]; // you result (id)
Connection:
define("HOST","localhost");
define("USER","mysql_username");
define("PASS","password");
$conn = mysql_connect(HOST,USER,PASS) or die("<h3>Sorry, could not connect to MySQL. Please Try Again</h3>");
$db = mysql_select_db(DBNAME,$conn) or die("<h3>Sorry, could not connect to Database. Please Try Again</h3>")
Query:
$query = "SELECT user_id FROM users WHERE user_email = = '" . $user_email . "'";
$result = mysql_query($query);
$row=mysql_fetch_assoc($result);
Your error comes because of the error in SQL query: you used = operator twice:
$query = "SELECT user_id FROM users WHERE user_email = = '" . $user_email . "'";
Must be:
$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";
Related
I have a query that checks if the inserted first name and last name exist in the database or not , I want to make the check for first name and last name or email , So if the inserted first name and last name exist then the user found and if the email only exist in the database then the user is found also , How to do that ?
Here is the code:
$query = "SELECT * FROM users WHERE first_name='" . $f_name . "' AND last_name='" . $l_name . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(empty($row)){
//some code to add the user to the database
}else{
//user is found
}
So I want the else mean that either (the first name and last name) or (the email only) doesn't exist in the database
$query = "SELECT * FROM users WHERE (first_name='" . $f_name . "' AND last_name='" . $l_name . "') OR (email = '" . $email . "')";
Hope this helps,
$query = "SELECT * FROM users WHERE (first_name='" . $f_name . "' AND
last_name='" . $l_name . "') OR (email = '" . $email . "')";
Edit -
Barclick Flores Velasquez his answer did not load for me yet, which is also correct.
Just need to append your query with email condition.
<?php
$query = "SELECT * FROM users WHERE (`first_name` = '".$f_name."' AND `last_name` = '".$l_name."') OR (`email_column_name` = '".$email."') ";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(empty($row)){
//some code to add the user to the database
} else {
//user is found
}?>
I would suggest you to use prepared statements to avoid SQL Injection
Object oriented style
<?php
$mysqli = new mysqli("localhost", "user_name", "password", "db_name");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE (`first_name` = ? AND `last_name` = ?) OR (`email_column_name` = ?) ");
$stmt->bind_param("sss", $f_name, $l_name, $email);
$result = $stmt->execute();
if($result->num_rows > 0){
//user is found
} else {
//some code to add the user to the database
}?>
Procedural style
<?php
$mysqli = mysqli_connect("localhost", "user_name", "password", "db_name");
$stmt = mysqli_prepare($mysqli, "SELECT * FROM users WHERE (`first_name` = ? AND `last_name` = ?) OR (`email_column_name` = ?) ");
mysqli_stmt_bind_param($stmt, "sss", $f_name, $l_name, $email);
$result = mysqli_stmt_execute($stmt);
if(mysqli_num_rows($result) > 0){
//user is found
} else {
//some code to add the user to the database
}?>
Quick Links
mysqli::prepare/mysqli_prepare
How can I prevent SQL injection in PHP?
I've been looking around stackoverflow and wasn't able to ever find a way that'd actually work. I have a simple php application
//Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
// Create connection to database
$db = new mysqli($servername, $username, $password, $database);
// Check connection for errors
if ($db->connect_error) {
die("<h1>Connection to database failed: " . $db->connect_error) . "</h1>";
};
$username = $json['statuses'][0]['user']['screen_name'];
$userid = $json['statuses'][0]['user']['id_str'];
$sql = "SELECT * FROM log WHERE userid='" . $userid . "' LIMIT 1";
if ($db->query($sql)->num_rows > 0) {
echo "<h4>This user already exists</h4>";
} else {
//Put the userid into the database
$sql = "INSERT INTO log (userid) VALUES ('" . $userid . "')";
if ($db->query($sql) === TRUE) {
echo "<h4>Added " . $username . " to the database</h4>";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
Currently it seems to be hit or miss. It'll work sometimes, other times a record will exist, and it'll still insert the userid again creating duplicates.
Like said #tadman Your code is BAD. Data from variable $json is directly inserted into query - this is not good...
Simple test:
I set :
$userid = "111111111a";
query:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
return TRUE because, this user doesn't exists in db,
or
$userID ='111111111\' OR \'1=1';
query:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
return TRUE because 1=1 is always true.
If column userid is INT type, $userid value is converted to 111111111 and inserted into log table
Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";
I have a query problem with hyphen character.
$user = "test-user";
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
test-user record is in table but query result coming empty. Also mysql error message is empty. What is wrong?
EDIT:
Thank you for answers. I apologize to everyone. I found the problem and I see now the problem is not in the query. Problem coming form regex.
if (preg_match("/^[a-z0-9]+$/i", $user)) //dash character not in regex
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
I've corrected the problem as follows:
if (preg_match("/^[a-z0-9\-]+$/i", $user)) //added \- to regex for dash
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
Just use mysql_real_escape_string to escape the data string.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
But I would also recommend using or die() syntax instead of the #mysql_query you have in place.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = mysql_query("SELECT id FROM table WHERE user='$user'") or die ("Error: " . mysql_error());
$p = mysql_query("SELECT id FROM table WHERE user='$user'");
if (!$p)
{
die('Could not query:' . mysql_error());
}
else
{
echo mysql_result($p>0);
}
try it
Try this:
$user = "test-user";
$q = mysql_query("SELECT id FROM `table` WHERE user='".$user."'")
or die(mysql_error());//no error message;
Full example with mysqli_:
$host = "";
$user = "";
$password = "";
$database = "";
$user_name_query = "test-user"; // If this value is from a form please read more about sql-injection.
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
// SELECT QUERY
$query = "SELECT id FROM `table` WHERE user='".$user_name_query."'";
mysqli_query($link,$query) or die("Query failed");
}
// close connection to database
mysqli_close($link);
Any difference if you change the query to:
$q = mysql_query("SELECT id FROM table WHERE user='".$user."'");
Unless I'm having a very slow Sunday I think you're searching for the literal string $user rather than the variable value.
I am completely new to MYSQL and PHP, so i just need to do something very basic.
I need to select a password from accounts where username = $_POST['username']... i couldn't figure this one out, i keep getting resource id(2) instead of the desired password for the entered account. I need to pass that mysql through a mysql query function and save the returned value in the variable $realpassword. Thanks!
EDIT:
this code returned Resource id (2) instead of the real password
CODE:
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = $_POST['username'];
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
echo "$new";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
It will be a lot better if you use PDO together with prepared statements.
This is how you connect to a MySQL server:
$db = new PDO('mysql:host=example.com;port=3306;dbname=your_database', $mysql_user, $mysql_pass);
And this is how you select rows properly (using bindParam):
$stmt = $db->prepare('SELECT password FROM accounts WHERE username = ?;');
$stmt->bindParam(1, $enteredusername);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$password = $result['password'];
Also, binding parameters, instead of putting them immediately into query string, protects you from SQL injection (which in your case would be very likely as you do not filter input in any way).
I think your code looks something like this
$realpassword = mysql_query("SELECT password
from accounts where username = '$_POST[username]'");
echo $realpassword;
This will return a Resource which is used to point to the records in the database. What you then need to do is fetch the row where the resource is pointing. So, you do this (Note that I am going to use structural MySQLi instead of MySQL, because MySQL is deprecated now.)
$connection = mysqli_connect("localhost", "your_mysql_username",
"your_mysql_password", "your_mysql_database")
or die("There was an error");
foreach($_POST as $key=>$val) //this code will sanitize your inputs.
$_POST[$key] = mysqli_real_escape_string($connection, $val);
$result = mysqli_query($connection, "what_ever_my_query_is")
or die("There was an error");
//since you should only get one row here, I'm not going to loop over the result.
//However, if you are getting more than one rows, you might have to loop.
$dataRow = mysqli_fetch_array($result);
$realpassword = $dataRow['password'];
echo $realpassword;
So, this will take care of retrieving the password. But then you have more inherent problems. You are not sanitizing your inputs, and probably not even storing the hashed password in the database. If you are starting out in PHP and MySQL, you should really look into these things.
Edit : If you are only looking to create a login system, then you don't need to retrieve the password from the database. The query is pretty simple in that case.
$pass = sha1($_POST['Password']);
$selQ = "select * from accounts
where username = '$_POST[Username]'
and password = '$pass'";
$result = mysqli_query($connection, $selQ);
if(mysqli_num_rows($result) == 1) {
//log the user in
}
else {
//authentication failed
}
Logically speaking, the only way the user can log in is if the username and password both match. So, there will only be exactly 1 row for the username and password. That's exactly what we are checking here.
By seeing this question we can understand you are very very new to programming.So i requesting you to go thru this link http://php.net/manual/en/function.mysql-fetch-assoc.php
I am adding comment to each line below
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"; // This is query
$result = mysql_query($sql); // This is how to execute query
if (!$result) { //if the query is not successfully executed
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) { // if the query is successfully executed, check how many rows it returned
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) { //fetch the data from table as rows
echo $row["userid"]; //echoing each column
echo $row["fullname"];
echo $row["userstatus"];
}
hope it helps
try this
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = mysql_real_escape_string($_POST['username']);
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
$row = mysql_fetch_array($new) ;
echo $row['password'];
if (!$new)
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<?php
$query = "SELECT password_field_name FROM UsersTableName WHERE username_field_name =".$_POST['username'];
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['password_field_name'];
?>
$username = $_POST['username'];
$login_query = "SELECT password FROM users_info WHERE users_info.username ='$username'";
$password = mysql_result($result,0,'password');