concatenate mysql select query with php variable? - php

I am trying to concatenate a MySQL SELECT query with PHP variable but got an error.
My PHP statement which gives an error is:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);
and error as:
( ! ) Notice: Undefined variable: info in C:\wamp\www\pollBook\poll\login.php on line 18
Call Stack
I don't understand where I missed the code.
When I write query without WHERE clause it works fine.

The reason why your code isn't working
You are attempting to use a variable, $info, that has not been defined. When you attempt to use an undefined variable, you're effectively concatenating nothing into a string, however because PHP is loosely typed, it declares the variable the second you reference it. That is why you're seeing a notice and not a fatal error. You should go through your code, and ensure that $info gets a value assigned to it, and that it is not overwritten at some point by another function. However, more importantly, read below.
Stop what you are doing
This is vulnerable to a type of attack called an SQL Injection. I'm not going to tell you how to concatenate SQL strings. It's terrible practice.
You should NOT be using mysql functions in PHP. They are deprecated. Instead use the PHP PDO Object, with prepared statements. Here's a rather good tutorial.
Example
After you've read this tutorial, you'll be able to make a PDO Object, so I'll leave that bit for you.
The next stage is to add your query, using the prepare method:
$PDO->prepare("SELECT * FROM tbl WHERE `id` = :id");
// Loads up the SQL statement. Notice the :id bit.
$actualID = "this is an ID";
$PDO->bindParam(':id', $actualID);
// Bind the value to the parameter in the SQL String.
$PDO->execute();
// This will run the SQL Query for you.

You are missing space before "AND " and you should use single quotes as suggested in other answers.
$result=mysql_query("SELECT user_id,username,add FROM users WHERE *username =".$user."AND* password=".$add);
Updated:
echo $sql = "SELECT user_id,username,add FROM users WHERE username ='".$user."' AND password='".$add."'";
$result=mysql_query($sql);

although there is no $info variable used in the query but you need to correct the query:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username ='" . $user . "' AND password='" . $add . "'");

First from the error its looks like one of your variables is not defined. .. check it. Second surround your parameters with ' for safer syntax.

This is because the variables you are using might not have defined above
So first initialize your variables or if its coming from somewhere else(POST or GET) then check with isset method
So complete code would be
$user = 123; // or $user = isset($user)?$user:123;
$add = 123456; // or $add = isset($add)?$add:123456;
And then run your query
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);

Related

update query is not working in php mysql

my query is:
$q = mysql_query("UPDATE `payment_details` SET `txnid`='$txnid',`amount`='$amount',`email`='$email',`firstname`='$firstname',`phone`='$phone',`productinfo`='$productinfo' where `id`='$id' ") or die(mysql_error());
but is is working when i change id = "1";
please any one can help with this problem.
The function mysql_query is deprecated in php 5.5.
Also it`s not very cool to put values in database like that.
You can use php PDO and bind values
Use the bindParam and prepare in the PDO to prevent SQL injection.
First of all check if $id has a value or not with var_dump($id);
Second thing is that don't put your variables inside single quotes otherwise it will be considered as a string.You need to concatenate your variables or you can use curly braces which serve as a substitution for concatenation, they are quicker to type and code looks cleaner.
Try this:-
$q = mysql_query("UPDATE `payment_details` SET `txnid`='{$txnid}',`amount`='{$amount}',
`email`='{$email}',`firstname`='{$firstname}',`phone`='{$phone}',`productinfo`='{$productinfo}'
WHERE `id`='{$id}' ") OR die(mysql_error());
It will work fine.
You should check the value of $id first and go from there.
var_dump($id);
If you get null or empty, there is your problem. If you get a non empty value, try to run the query in your mySQL client with the value that you got.
Also, it would help to see the error message that you are getting :)
Good luck.

Strange Error in mysql_query() function in PHP (And clause in Query)

When I add AND operator in mysql_query() function, it stops working and anything after that stops working!
For Example:
When i wrote this:
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
The above query runs successfully !
But when i do this :
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' AND username = '$_POST[uname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
I get Null output!
I think the "AND" operator is not working!!!
please help me with this!!
Have a look at my complete code and Database Snapshot!
Click here
If it is returning NULL then probably the record doesn't exists. Try to output this query on the screen and post the raw query here.
Maybe your search needs a LIKE instead of a =
Likely, the row(s) you are looking for do not exist.
The AND is a boolean operator that requires that both expressions have to evaluate to true. In the context of your query, that means for a row to be returned, both of the conditions have to be true on that single row.
I suspect that you may want an OR those two conditions. Did you want to return only rows that meet both criteria, or did you want any rows that have fname with a certain value, along with any rows that have uname of a specific value? If the first query is returning rows, then replacing AND with OR should return you some rows.
For debugging this type of problem, generate the SQL text into a variable, and then echo or var_dump the SQL text, before you send it to the database.
e.g.
$sql = "SELECT * FROM chat1 where friendname = '"
. mysql_real_escape_string($_POST['fname'])
."' ";
echo "SQL=" . $sql ; # for debugging
Take the text of SQL statement that's emitted to another client, to test the SQL statement, to figure out if the SQL statement is actually returning the resultset you expect it to return.
(In your code, reference the $sql in the function that prepares/executes the SQL statement.)
Follow this pattern for all dynamically generated SQL text: generate the SQL text into a variable. For debugging, echo or var_dump or otherwise emit or log the contents of the variable. Take the SQL text to another client and test it.
Dumping code that isn't working on to StackOverflow is not the most efficient way to debug your program. Narrow down where the problem is.
How to debug small programs http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
NOTES
You probably want to verify that $_POST['fname']) contains a value.
It's valid (SQL-wise) for a SELECT statement to return zero rows, if there are no rows that satisfy the predicates.
Potentially unsafe values must be properly escaped if you include them in the text of a SQL statement. (A better pattern is to use prepared statements with bind placeholders, available in the (supported) mysqli and PDO interfaces.
Also, use single quotes around fname.... e.g.
$_POST['fname']
^ ^

query multiple columns php/mysql

new to php and am enrolled on a course, so can ask tutor tomorrow if this is more complicated than i think it might be!
I have an sql query, and it works fine. But I am trying to add and 'and' in the select statement.
This is what I have at the minute
$query = "SELECT * from table1 where table1.age <= " . $_POST['min_age'] ;
I have a 'region' input on my linked html page and want results to be returned only if the min_age and region values match those inputted by the user.
I have tried adding an 'and where' but it doesn't work and I am not sure if it is because of the multiple "'s or if what I am trying to do needs a different method?
Thanks
If you need multiple conditions, just separate them with AND:
... WHERE table1.age <= ? AND table1.region = ?
No need to use WHERE again. Just like you wouldn't need to use if() more than once if you were writing a complex condition in PHP.
PS: This isn't directly related to your question, but you should get into the habit of not putting $_POST or $_GET variables directly into your SQL queries. It's a good way to get hacked! Ask your tutor about "SQL injection," or read my presentation SQL Injection Myths and Fallacies.
I know you're just starting out, but if you were training to be an electrician, you would place a high priority on learning how to avoid being electrocuted or how to avoid causing a fire.
Here's how I would write your query using mysqli. One advantage of using query parameters is you never need to worry about where you start and end your quotes.
$query = "SELECT * from table1 where table1.age <= ? AND table1.region = ?";
$stmt = $mysqli->prepare($query) or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->bind_param("is", $_POST["min_age"], $_POST["region"]);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
The other good habit I'm showing here is to always report if prepare() or execute() return an error.
If you must interpolate variables into your SQL, first make sure you protect the variables either by coercing the value to an integer, or else by using a proper escaping function like mysqli_real_escape_string(). Don't put $_POST variables directly into the string. Also you don't have to stop and restart the quotes if you use PHP's syntax for embedding variables directly in double-quoted strings:
$age = (int) $_POST["min_age"];
$region = $mysqli->real_escape_string($_POST["region"]);
$query = "SELECT * from table1 where table1.age <= {$age}
AND table1.region = '{$region}'";

2nd MySQLi Query causes a "Call to a member function execute() on a non-object"

I've got a strange problem. There are 2 queries.
$sql = "SELECT `content_auftrag_id`
FROM `content`
WHERE `content_id` = '".$content_id."' LIMIT 1";
$ergebnis = $db->prepare( $sql );
$ergebnis->execute();
$ergebnis->bind_result( $content_auftrag_vorhanden );
$content_auftrag_id = "test";
$sql = "UPDATE `content` SET `content_auftrag_id` = '".$content_auftrag_id."'
WHERE `content_id` = '".$content_id."'";
$ergebnis2 = $db->prepare( $sql );
$ergebnis2->execute();
When I use them both, then an error occurs for the second one. If I only run the the second, then it works fine. How can it be that both together cause an error?
All variables are there and correct.
Thanks!
Okay, I think you didn't quite got the idea behind PreparedStatements. You shouldn't directly insert the parameters in your SQL-String, but use ?-placeholders and bind them in the Query using the bind_param()-method.
Your error seams to appear here:
$ergebnis2 = $db->prepare( $sql );
This function returns false if it wasn't successful. You should check if the value of ergebnis2 is not false.
Also, you should use the error-method to see the last appeared MySQL-Error.
You can only work on one prepared query at a time, so to speak. See Mysqli::execute() method:
"When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries."
You can also use the store_result() method to remove this block as well to perform the next query.
Also, take heed from those who warn you about abusing prepared statements like your example. Though it works without error if you don't actually have any parameters to bind to, it basically throws sql injection prevention out the window.
If $ergebnis2 is 'not an object', then I guess it must be false. Which means the prepare() call failed for whatever reason.
What does $db->error return after you have called the 2nd prepare?
Always check your return values, its basic debugging

How should I write PHP $_POST vars in a mysql_query function?

In accessing my database, I have the user fill out a form, and in the target page, the posted values are used in the resulting MySQL query.
$query = mysql_query("SELECT pass FROM database WHERE user='$_POST[user]'");
However, for some reason or another, MySQL doesn't like my using a $_POST variable in the command, and it only works if I define (for example) $user = $_POST['user'];, and then put $user directly in the SQL command.
On the other hand, I can use $_POST values in INSERT statements where specific column names are not required:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', '$_POST[user]'");
If I try an INSERT statement where attributes are defined (e.g. user='foo'), then the same problem appears.
What am I doing wrong in my SQL query that causes the command to error out when run, but works with the specific method of formatting an INSERT command?
Hopefully, it's not "tough luck, looks like you have to assign all of your posted values". Heh.
First of, watch out for SQL Injections!
Now, to answer your question try doing this instead:
$query = mysql_query("SELECT `pass` FROM `database` WHERE `user` LIKE '" . mysql_escape_string($_POST['user']) . "';");
You were doing a couple of things wrong:
using the = operator instead of LIKE operator
not enclosing the value in the SQL query with '
not enclosing the user index in the $_POST array with '
PS: You should use mysql_real_escape_string() instead of mysql_escape_string()!
You're simply inserting a variable into a string, so it shouldn't matter which command you're putting it into.
There are a few issues to point out.
One, you might want to use the {} format for array variables. You don't use quotes around the arrray key names in this format.
$query = mysql_query("SELECT pass FROM database WHERE user='{$_POST[user]}'")
Two, you'd never want to make a query like that because you are open to sql injection holes. Consider, what if $_POST['user'] was "cow';drop table database;--"?
You must either run mysql_real_escape_string on the POST input before putting it into your query, or check out using PHP PDO with prepared statements.
One way to do format your string which provides a bit of structure is to use sprintf.
$query=mysql_query(sprintf("SELECT pass FROM database WHERE user='%s'",mysql_real_escape_string($_POST['user'])));
Use PDO - it provides much better API to communicate with DB.
If you're using mysql_*() functions always remember to filter (mysql_real_escape_string()) any data that comes from untrusted source (like user)
Pay more attention to how your code looks like. Just compare the following listings:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ")");
$query = sprinf('INSERT INTO database VALUES ("foo", "bar", "%s", "%s", "%s")',
mysql_real_escape(...), ...);
Do I have to explain which one is better to read, modify or understand?
Why not check and see what mysql_error() has to say about it? If your query is invalid, mysql_error() will return a nice blob of text telling you exactly what went wrong.
As for MySQL not liking the POST var if you insert it directly for some runs, but not others, then you should make sure you're using consistent data and setups for each test. If some test are done using a GET, then your POST vars will be empty. If you're using different user names for each test, then see if what's consistent between the ones that fail.
And as mentioned above, read up about SQL injection and how your query is just begging to be subverted by a malicious user.
Try
$query = mysql_query("SELECT pass FROM database WHERE user=" . mysql_real_escape_string($_POST['user']));
and
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ")");
Its always a good idea to sanitize anything received through $_GET or $_POST

Categories