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);
Related
I have this function:
function word($arg){
echo ''.$arg.'';
//echoes test
require ('config.php');
$requestSQL = mysql_query("SELECT * FROM db where eng LIKE '%$arg%' order by id ASC LIMIT 10", $connection);
while ($row = mysql_fetch_array($requestSQL))
{
echo ''.$row['id'].': '.$row['eng'].'<br>';
}
}
Gets triggered by:
$number = $explode[1];
word($number);
But doesn't echo values from the database, nothing at all.
If I echo $arg (in the function), it shows the value. If I replace in my sql query: '%$arg%' with '%test%', it echoes the correct value.
Is the '%$arg%' syntax wrong?
You should use a proper concat
"SELECT * FROM db where eng LIKE concat('%', '$arg', '%') order by id ASC LIMIT 10"
It's pretty simple, all you do is: LIKE %{$arg}%. Because I am assuming that $arg is a text value. If a variable is a text value then you must do this to keep it working. You wrap text variables in {}.
Also, never . . . EVER use mysql_*, you should move to mysqli_* or PDO/OOP. It's just good practice.
Update
You can't use variables within mysql_query("", $connection) quotes. Instead, do this:
$query = "SELECT * FROM db WHERE eng LIKE '%{$arg}%' ORDER BY id ASC LIMIT 10";
// then use this variable as a replacement for the quotes in the mysql_query().
$set = mysql_query($query, $connection); // like so . . .
// mysql_fetch_assoc() is the same as mysql_fetch_array().
while($row = mysql_fetch_assoc($set)) {
echo "".$row['id'].": ".$row['eng']."<br>";
}
I'm so stupid, actually $explode[1]; was returning the correct value but had a blank line in the source code. So I had to use trim and now it works.
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
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
this is my code:
$Line = mysql_real_escape_string(postVar("showline"));
$Model = mysql_real_escape_string(postVar("showmodel"));
$NIK = mysql_real_escape_string(postVar("showNIK"));
$sql ="SELECT NIK,Line,Model FROM inspection_report";
$sql.="WHERE NIK='".$NIK."' AND Model LIKE '%".$Model."%' AND Line='".$Line."'";
$sql.="ORDER BY Inspection_datetime DESC LIMIT 0 , 30";
$dbc=mysql_connect(_SRV, _ACCID, _PWD) or die(_ERROR15.": ".mysql_error());
mysql_select_db("qdbase") or die(_ERROR17.": ".mysql_error());
$res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() ); // submit SQL to MySQL and error trap.
$num=mysql_affected_rows();
$objJSON=new mysql2json();
print(trim($objJSON->getJSON($res,$num,'aaData',false)));
mysql_free_result($res);
at firebugs shows that connection to process page ok...but at response show error..
where is my fault?
I am assuming that is PHP.
Add the command echo $sql; after your lines above. I bet your query is malformed, i.e. no space between the end of the FROM clause and the WHERE. Same with ORDER BY. Happens all the time ;)
What Jason has said is good and will show you where the error is, which looks like a lack of spaces in the line breaks. Add a space before WHERE and another before ORDER
I have found a lot easier to write and read my SQL statements by declaring the SQL String within a single set of quotes as in:
$sql ="SELECT NIK,Line,Model FROM inspection_report
WHERE NIK='$NIK' AND Model LIKE '%$Model%' AND Line='$Line'
ORDER BY Inspection_datetime DESC LIMIT 0 , 30";
This method will also solve your problem with missing spaces between lines.
As stated in other answers, you're lacking spaces in your query:
$sql = "SELECT .... inspection_report";
$sql .= "WHERE NIK=..."
etc...
will generate a query string:
SELECT ... inspection_reportWHERE NIK=...
^^--- problem is here
Notice the lack of a space before the WHERE clause. You have to either modify your string concatenation statements to explicitly include the space:
$sql = "SELECT ... inspection_report";
$sql .= " WHERE NIK=..."
^---notice the space here
or use alternative syntax to build the string. For multi-line string assignments, it's generally always preferable to use HEREDOCs, unless you need to concatenate function call results or constants into the string:
$sql = <<<EOL
SELECT ... inspection report
WHERE NIK=...
EOL;
PHP will honor the line breaks inside the heredoc, and MySQL will silently treat them as spaces, preserving the integrity of your query.
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