sql returning no results - php

The following code is returning no results where I use the variable in the code of $dep if I manually put the value in of 1 it returns the expected result. I have tried it with no quotes single quotes and double quotes. I have looked though loads of examples and I cannot see what I am doing wrong
$dep = 1;
if (!$names) {
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
$res = db_query($sql);

I'm pretty sure your error is related to wrong quotes used.
In your code, you write
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
After FROM, you are using single-quotes('), but your whole query has been enclosed into double-quotes("), so that creates the issue.
It should be:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ".TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
EDIT: Forgot to point out you should seriously use PDO or any other SQL Injection prevention methods. If, under any circumstance, your $dep variable could be sent via a public form, you could end up by having your DB dumped in the best case.

There's a syntax error in the second line of the query - if you want single-quotes in the query, then you need to enclose it all in double-quotes:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ' .TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
By the way, building a query like this, using string concatenation, is a REALLY BAD IDEA and leaves you open to SQL injection attacks - you should use prepared statements and parameters instead.

First as Fred -ii says make sure the if statement is executing properly. Then if dept_id is an integer value then you should not need the single quotes as scaisEdge says. Otherrwise the SQL looks fine. Make sure that there are in deed records in the database for the dept_id that is being passed in.

Related

mysqli_stmt_bind_param() data not supplied when a question mark is a part of the query

Similar questions have been asked many times, but after reading almost every of these for over 5 hours, i have not found a suitable reply for my problem.
Im not an experience php / mysql developer, but i ve managed similar situations with the use of mysqli_stmt_bind_param() func.
Here is the query:
$query = 'SELECT Recipes.* , Categories.* FROM `Recipes` JOIN `Categories` ON JSON_EXTRACT(Recipes.category, \'$.category\') = \'Category ?\' WHERE Categories.category = ?';
I use this php code:
if ($stmt = mysqli_prepare($dbManager->getDBInstance(), $query)){
mysqli_stmt_bind_param($stmt,"ii", $id, $id);
}
Because i have a model on the client side like:
{
"category" : "...",
"recipes" : [{...},{...}]
}
The error is: Fatal error: Uncaught mysqli_sql_exception: No data supplied for parameters in prepared statement
I have already made similar queries with many more parameters, without any error: however, this is the first time i use the JSON_EXTRACT func from mysql.
I believe the error is caused by the $. which is not escaped correctly. The parameters to be replaced reference to the same variable, $id, which is an integer, and gets used for string interpolation in the first case ('Category 1') and as number after the WHERE clause.
Consider that, by not using mysqli_stmt_bind_param, the same query on phpmyadmin returns what i want, but that would open my code to mysql injections, which i want to avoid.
Also, notice that if i pass just one parameter to the function, the script gets executed (with wrong results), like if the query gets truncated at some point... i properly escaped every single quote, and even tried with double quotes, but the error is always the same.
Any hint on how to prevent the injection and achieve the result would be highly appreciated, because i really can't figure it out by myself.
Thank you
You have two parameters in the call to mysqli_stmt_bind_param(), but there's only one placeholder in $query. The first ? is inside quotes, so it's treated literally, not as a placeholder.
You can use CONCAT() to concatenate a string literal with a placeholder, so change it to:
$query = '
SELECT Recipes.* , Categories.*
FROM `Recipes`
JOIN `Categories` ON JSON_EXTRACT(Recipes.category, \'$.category\') = CONCAT(\'Category \', ?)
WHERE Categories.category = ?';
A placeholder can represent a complete data literal only. To put it simple - anything you would write in quotes (or a number). So it shouldn't be 'Category ?' but just ? where Category could be concatenated in PHP.
$query = 'SELECT * FROM `Recipes` JOIN `Categories` ON
JSON_EXTRACT(Recipes.category, \'$.category\') = ?
WHERE Categories.category = ?';
$stmt = mysqli_prepare($dbManager->getDBInstance(), $query);
$category = "Category $id";
mysqli_stmt_bind_param($stmt,"si", $category, $id);

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}'";

SQL query escaping + codeigniter

I'm using codeigniter and most of the time use active record for my queries (which automatically escapes them), but this query doesn't seem to fit neatly into it because of the variable. So I need to figure out how to escape the query manually.
Codeigniter docs suggest escaping the queries this way:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
My original query
$sql = "SELECT * FROM (`user_language`) WHERE `user_id` = '{$id}'";
My escaped query
$sql = "SELECT * FROM (`user_language`) WHERE `user_id` = '{$id}' VALUES(".$this->db->escape($user_language).")";
But I'm having trouble getting the syntax right. Error messages are:
PHP error message: Undefined variable: user_language
SQL error: syntax wrong...near 'VALUES(NULL)' at line 1
$sql = "SELECT * FROM `user_language` WHERE `user_id` = " . $this->db->escape($id);
if you want to select the language of the user given by $id it should work that way.
dealing with numbers an alternative would be:
$sql = "SELECT * FROM `user_language` WHERE `user_id` = " . (int)$id;
codeigniter does also support prepared statements as "query bindings":
The secondary benefit of using binds is that the values are
automatically escaped, producing safer queries. You don't have to
remember to manually escape data; the engine does it automatically for
you.
I'm confused why you say you cannot use the Active Record class with CI, this is a simple SQL call (example below uses method chaining):
$this->db->select('*')->from('user_language')->where('user_id', $id);
$query = $this->db->get();
Your $id is then escaped properly, and you mitigate any injection.
Personally I use AR whenever possible, it allows me to write quick efficient code, and not worry about the bad things with SQL calls (custom queries).

PHP sql query syntax

Noticed a small issue in the syntax of a sql query, here's how it goes:
$email = "name_lastname#server.com";
$query = "Select * From Users Where email=".$email;
This does not work, the query has been tested and works fine, however this essentially evolves to :
Select * FROM Users WHERE email=name_lastname#server.com ;
Which yields a null result.
To execute it the right way, I add a twist to the syntax of my $email variable, essentially as:
$email = "\"name_lastname#server.com\"";
Once I specify quotations within the string variable, that is when it executes as expected yielding the desired result.
I am not sure if this is the most aesthetic way to go about approaching my syntax for query execution, and I do think there are alternatives. Grateful to those who shed a light on this
Try this instead:
$query = "Select * From Users Where email='$email'";
Or:
$query = sprintf("Select * From Users Where email='%s'", $email);
Or:
Many many other ways....
String queries need a single quote around the search criteria. Assuming MySQL: http://dev.mysql.com/doc/refman/5.0/en/string-syntax.html
$email = "name_lastname#server.com";
$email = "'" . mysql_real_escape_string($email) . "'";
$query = "Select * From Users Where email=".$email;
non quoted variables like that will be read as int. Always quote all strings. you don't need to escape doubles like that when singles will suffice.
$query = "SELECT * From Users WHERE email= '".mysql_real_escape_string($email)."'";
Why not do:
$email = "name_lastname#server.com";
$query = "Select * From Users Where email = '$email'";
Your solution gets at the right principle: SQL needs the email address to be enclosed in quotes because it's a string. My suggestion for making the code more elegant would simply be to put the quotes in the string containing the query, not the one containing the email address.
$email = "name_lastname#server.com";
$query = "Select * From Users Where email=\"".$email."\"";
The quote marks aren't part of the email address, they're part of the query. If you do it this way, you won't have extraneous quotes if you try to use $email for something else, and you won't have to remember to put quotes around every other email address that you pass into the same query.
Also, you might want to check out mysqli, which handles queries in a slightly different way and as a side effect, eliminates all this fooling around with escaping your strings.
PS - I agree with the folks who suggested using single quotes instead of escaped double quotes. But SQL does accept double quotes (at least on my system) so I stuck with the convention you were using.
The best way to avoid quote problems is to prepare the statement in phpMyAdmin and then generate the PHP source query:
$email = "name_lastname#server.com";
$sql = 'SELECT * FROM `Users` WHERE `email` = '.$email;
More info:
http://www.packtpub.com/article/multi-table-query-generator-using-phpmyadmin-mysql

What's wrong in this simple PHP SQL sentence?

i want to recober all the users with "blo" in their full name, for example: "Pablo"
I pass the "blo" parameter with user PHP parameter:
$q=mysql_query("select * From user Where fullName Like '%'".$_REQUEST['user']."'%'",$link );
something is wrong in the php SQL sentence, because when i try the sentence with the argument "blo" on my SQL database, i see that the SQL sentence is correct, because it returns me correct result, this is the sentence with the argument "blo" on it: select * From user Where fullName Like "%blo%"
i'm sure that the PHP is receiven the "blo" parameter correctly, then, it have to be a sintax error of the SQL sentence on the PHP.... but i can't find it
EDIT : OK!! the last sentence is solved, but now i have this new sentence with the same problem, it have a error but i dont know where
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%' AND email NOT IN (select pp.fk_email2 from permission pp where pp.fk_email1='".mysql_escape($_REQUEST['mymail'])."') AND email NOT LIKE '".mysql_escape($_REQUEST['mymail'])."' ",
mysql_real_escape_string($_REQUEST['user']));
SQL requires single quotes to indicate a string for comparison, and the wildcard character (%) must be included inside of those single quotes. Double quotes are used for column and table aliasing only, if at all.
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%'",
mysql_real_escape_string($_REQUEST['user']));
$q = mysql_query($query, $link);
Secondly, you're leaving yourself open to a SQL injection attack by not sanitizing the user request variable. Always use mysql_real_escape_string when dealing with strings being submitted to a MySQL database.
You have the quotes messed up. use this:
$q=mysql_query('SELECT *
FROM user
WHERE fullName LIKE "%' . $_REQUEST['user'] . '%"',$link );
BTW, this is bad practice. You are using un-escaped input in your query and are open to SQL injection.
It looks like your quotes are off.. try something like...
$q=mysql_query("select * From user Where fullName Like '%".$_REQUEST['user']."%'",$link);
Also, you will want to make sure that the incoming param is sql-escaped to prevent sql injection. I don't know php, but it's probably something similar to...
$q=mysql_query("select * From user Where fullName Like '%".mysql_escape($_REQUEST['user'])."%'",$link);
I think it must be ... Where fullname like '%" . $_REQUEST['user']."%'"...
with the % symbol inside the simple quotes.
#AndroidUser99: Change the query to --
$q = mysql_query("select * from user Where fullName like '%" . $_REQUEST['user'] . "%'", $link);
Update
I think we may need more code since none of the answers seem to be 'working'. Is the database link even being instantiated in $link? If there are errors what are they?

Categories