Cannot pass a string to a SQL Query - php

I have the following code:
$RefEquipamento = mysql_real_escape_string($_GET['ID']);
mysql_select_db($database_connLOOPGEST, $connLOOPGEST);
$query_rs_equipamento = sprintf("SELECT * FROM clientes_listaequipamentos WHERE referenciacliente = $RefEquipamento ORDER BY datacriacao_loop DESC LIMIT 1");
$rs_equipamento = mysql_query($query_rs_equipamento, $connLOOPGEST) or die(mysql_error());
$row_rs_equipamento = mysql_fetch_assoc($rs_equipamento);
$totalRows_rs_equipamento = mysql_num_rows($rs_equipamento);
echo json_encode($row_rs_equipamento);
I'm not an expert in PHP or MySQL, I'm trying to learn something. I'm using Dreamweaver.
The code above works when I pass a number as an argument (for ex. If $RefEquipamento is 200456) this works fine, but when I tried to pass a string (let's say I'm passing the string "equip1" this doesn't work, the echo gives me the following message:
"Unknown column 'equip1' in 'where clause'"

try:
$RefEquipamento = "'" . mysql_real_escape_string($_GET['ID']) . "'";
so mysql will handle it as a string.
OR
$query_rs_equipamento = sprintf("SELECT * FROM clientes_listaequipamentos WHERE referenciacliente = '$RefEquipamento' ORDER BY datacriacao_loop DESC LIMIT 1");

If you send to MySQL command a word, without marking with --> ' <---- MySQL Understand you are giving the name of a field or columns.
Remember that allways you need to past a word as variable, you need mark it.
the number don't need special mark
Yoni Hassin response is the solution, mark it as answer

Related

SQL query not returning any results when it should

I have an sql query in my php script that has this line in it:
WHERE beerStyle = \"$styleName\" AND rating > 0
The style name that is being looked up is:
Fresh "Wet" Hop Ale
Which is being stored exactly has written above in my database. My problem is I think somehow the quotes are getting mixed up when it looks in the DB, so it thinks there are now styles with that name.
Make use of mysqli_real_escape_string()
$styleName=mysqli_real_escape_string($styleName);
and your query goes like.
WHERE beerStyle = $styleName AND rating > 0
Perhaps you may try
$query = "SELECT * FROM beers WHERE beerStyle = '" .$styleName. "'";

Variable mysql statement in php

I have a variable that is a filter for my query:
$filterString.=" AND venue = ".$venue;
And I want this variable (when called) to add the AND filter statement to my query.
My query is as follows (with the failed attempt):
mysql_query("SELECT * FROM event
WHERE city = '$city' " . $filterString . "
ORDER BY date ASC");
I think the venue needs to be surrounded by single quotes:
$filterString.=" AND venue = '".$venue.".";
However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.
You could use:
$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';
Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.
To answer your other comment question:
WHERE 1
is a valid condition that works like Anything

Session variable is not working in MySQL statement

I am trying to use session variable($_SESSION['asc_id'], which holds some value like "AS0027001") in an SQL statement, but it is not working.
When I hardcode the value, it is providing results.
Can anyone please correct me.
MySQL query which is not working
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "$asc_id"
and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Mysql query which is working
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "AS0027001" and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Variable substitution only works within double quoted strings, not single quoted ones. In other words, you should do;
$rs = mysql_query("select .... and asc_id = '$asc_id' and ... limit 0,10", $dblink);
Btw, you did make sure the value doesn't include any characters that may lead to SQL injection, right? Otherwise you should use mysql_real_escape_string to make sure before inserting it into a query.
When you print the strings, it will be clear. When the question is reformatted to leave the SQL readable, the problem is clear. (The first rule for debugging SQL statements is "print the string". A second rule, that makes it easier to comply with the first, is always put the SQL statements into a string which you pass to the SQL function.)
You use the . notation to embed the request term in the string; you don't use that to embed the $asc_id into the string. You should also use mysql_real_escape_string() on the session ID value to prevent SQL injection.
First print the variable $asc_id . If it displays nothing, session is unavailable . In that case you missed session_start() in top of the current executing page .
From the SQL query, you cannot replace the value of a variable inside single quoted string .
Use . symbol for mixing string value with variable or use double quoted string . I prefer first one .
For troubleshooting , simplest method is printing variable values. From the result , you will understand what is missing .
Thanks
Try this. from the comment you added, I modified it like this
session_start(); //add this if you did not do it yet
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query("select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = '$asc_id'
and lname_fname_dob like '".
mysql_real_escape_string($_REQUEST['term']) .
"%' order by lname_fname_dob asc limit 0,10", $dblink);

PHP mysql - ...AND column='anything'...?

Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.

MySQL Query in CodeIgniter with Session ID

Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2

Categories