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'
Related
I'm trying to select and echo a single field.
This is my code when I'm trying it
session_start();
$query = "select id from user where username = ".$_SESSION['username'];
$result = mysql_query($query);
$admin_id = mysql_fetch_array($result);
echo $admin_id['id'];
When I run that code, this warning text appears
mysql_fetch_array() expects parameter 1 to be resource, boolean given in ......
How should I do it?
You should use quotes when you assign values in sql queries .
$query = "select id from user where username = '{$_SESSION['username']}'";
Or
$query = "select id from user where username = '" . $_SESSION['username'] . "'";
However, it is not a good practice so you better look forward prepared statements to reduce sql injection vulnerability : http://ru2.php.net/pdo.prepared-statements
Try this:
$username = $_SESSION['username'];
$query = "select id from user where username = '$username'";
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());
}
Is there any way to store mysql result in php variable? thanks
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
then I want to print selected userid from query.
Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
There are a couple of mysql functions you need to look into.
mysql_query("query string here") : returns a resource
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.
Links:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-array.php
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
$query="SELECT * FROM contacts";
$result=mysql_query($query);
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
http://php.net/manual/en/pdo.prepared-statements.php PDO
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.
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
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.