I want to check for the username in the users table. If it's found, then I want to get the id. Otherwise, I want to insert the username as a new record, then get the id.
Here's my code:
<?PHP
$sql = "SELECT id FROM users where username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
if($result){
$row = mysql_fetch_array($query);
$userid = $row["id"];
}else{
$sql = "insert into users set username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$userid = mysql_insert_id();
}
?>
How can I optimize or combine these MySQL queries?
Can I select and insert in the same query?
and would it be better and faster?
If you want this to be fast make sure you index username.
It's better to INSERT first, with the assumption that the username does not exist. If any error is caused by a duplicate conflict, SELECT the existing row.
<?php
$sql = "INSERT INTO users SET username = '"
. mysql_real_escape_string($username) . "'";
$query = mysql_query($sql);
if ($query === true) {
$userid = mysql_insert_id();
} else {
if (mysql_errno() != 1022) { // this is the duplicate key error code
die(mysql_error());
}
$sql = "SELECT id FROM users where username = '"
. mysql_real_escape_string($username) . "'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($query);
if ($row !== false) {
$userid = $row["id"];
}
}
?>
The reason this is better is that if you select then insert, someone else might insert the username in the moment between your two SQL statements.
Of course you should have a UNIQUE constraint on users.username.
Re your comment: yes, it should be faster that your script. When there is no duplicate username (which is probably more common), you don't have to run the SELECT.
The best way to optimize an SQL query is not to run it at all.
Related
$sql = "SELECT email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$email1 = $row[0];
$email2 = $row[1];
Just trying to select email from 2 columns and identity which email belongs to which username. Email1=user1 and email2=user2, is what I seek.
$sql = "SELECT username,email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($query))
{
$email[ $row[0]] = $row[1];
}
mysqli_free_result($row);
Hope it will help..
expected output
$email['user1']= email1
$email['user2']= email2
As written, each row would contain only a single email address.
You'd be better served selecting an additional column that identifies the user, such as an id or username.
Then each row would contain both the email and the identifying data associated with that email. If more than one row is matched, you'll need to fetch additional rows to determine that, or else use an aggregate query.
$sql = "SELECT username,email FROM users WHERE username='$user1' OR username='$user2' LIMIT 2";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($query)){
$username = $row[0];
$email = $row[1];
// do some checking
}
Also, be sure the values of $user1 and $user2 are safe before sending...
I'm working with a system that assigns files to users. Problem is, that the response, userid, is always 0.
$user = htmlentities($_SESSION['username']);
$sql = "INSERT INTO `files`(
`userid`,
`filename`,
`filesize`,
`filetype`,
`filepath`
)
VALUES
(\"". get_user_id($user). "\",\"".
$_FILES['userfile']['name']. "\",\"".
$_FILES['userfile']['size']. "\",\"".
$_FILES['userfile']['type']. "\",\"".
$fileadress.
"\")";
Function get_user_id
function get_user_id($user){
mysql_connect(HOST, USER, PASSWORD)
or die(mysql_error());
$sqlinit = "USE secure_login";
mysql_query($sqlinit);
$sql = "SELECT `id` FROM `members` WHERE `username` = '". $user."'";
$result = mysql_query($sql);
//mysql_fetch_array($result);
echo mysql_error();
$userid = $result;
return $userid;
}
No errors, no warnings, everything else is working fine, only userid is showing always 0, even when id in members is 1,2 etc. Am I missing something? In both tables, userid and id are int.
mysql_query() returns you a mysql object, you put this object in the result variable. So if you do $userid = $result; you just duplicate the array to a new variable.
You're not accessing correctly to the element, you should write instead : $userid = $result['id'];
Take the habit to employ var_dump($result); to see what's exactly in you're variable (here result)
EDIT:
$sql = "SELECT id FROM members WHERE username = '". $user."'";
$queryRes = mysql_query($sql);
$result = mysql_fetch_array($queryRes);
$userid = $result['id'];
I believe you have to use $userid=$result['id']
As per your table, the right index would be userid
i.e:
$userid = $result['id'];
I don't understand this because I'm just getting into query's and php.
I'm trying to get the user's ID from the database and set that equal to a different users friendreq column.
Don't worry about me not escaping properly, this is only a test so I can practice! Thank you! (Although I'm not sure what escaping is, I'm going to do my research!)
$usernameID = "SELECT Id FROM Users WHERE Username = '$username'";
$sql = "UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'";
$result = mysqli_multi_query($con, $usernameID, $sql);
if(!$result)
{
echo 'Failed';
}
else
{
echo 'Friend added!';
}
According to the PHP reference of mysqli_multi_query your two queries need to be concatenated with a semicolon. You're passing each query as its own parameter.
Use the following instead:
$result = mysqli_multi_query($con, $usernameID . "; " . $sql);
This will concatenate your two queries, so that it's the following:
SELECT Id FROM Users WHERE Username = '$username'; UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'
I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}
I am using a MySQL table called "login" that includes fields called "username" and "subcheckr."
I would like to run a PHP query to create a new variable equal to "subcheckr" in the table where "username" equals a variable called $u. Let's say I want to call the variable "$variable."
How can I do this? The query below is what I have so far.
Thanks in advance,
John
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
I don't know if I understood correctly but if:
Just do something like this.
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
In case you don't know, your query is vulnerable for SQL injections. Use something like mysql_real_escape() to filter your $u variable.
Is this what youa re looking for?
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$subcheckr = $row['subcheckr'];
$sqlStremail = mysql_query("SELECT subcheckr FROM login WHERE username = '$u'");
$result= mysql_fetch_array($sqlStremail);
$some_variable = $result['subcheckr']; // the value you want
You can do:
// make sure you use mysql_real_escape to escape your username.
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
// run the query.
$result = mysql_query($sqlStremail );
// See if the query ran. If not print the cause of err and exit.
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
// if query ran fine..fetch the result row.
$row = mysql_fetch_row($result);
// extract the field you want.
$subcheckr = $row['subcheckr'];
You can write
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
$result = mysql_query($sqlStremail );
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$row = mysql_fetch_row($result);
$subcheckr = $row['subcheckr'];
$variable = array_pop(mysql_fetch_row(mysql_query("SELECT subcheckr FROM login WHERE username = '$u'")));
Only if username is unique