mysql:connection OK but response error - php

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.

Related

PHP mysql query using wildcards

I am in search of a way to use wildcards with the following mysql query.
public function getSetsOnMonth($setsId, $setsDate, $offset, $count)
{
$sql = sprintf("SELECT * FROM " . $this->_prefix . "media_set AS f
INNER JOIN " . $this->_prefix . "media_set_sets_assoc AS fs
ON fs.set_id = f.set_id AND fs.sets_id = '%s'
WHERE f.posted LIKE '%s'
AND f.is_active = 1
ORDER BY f.set_id DESC
LIMIT %s, %s",
mysql_real_escape_string($setsId),
mysql_real_escape_string($setsDate),
mysql_real_escape_string($offset),
mysql_real_escape_string($count));
echo $sql; exit;
$rs = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_object($rs)) {
$rows[] = $row;
}
mysql_free_result($rs);
return new XXX_Model_RecordSet($rows, $this);
}
What i am looking to do is by month so that would be (where f.posted LIKE '%s') is located
I have tried using the % in various ways and it always errors.
For instance (where f.posted LIKE '%s %') returns this error (Warning: sprintf(): Too few arguments in..).
I have also tried to use (where f.posted LIKE '$setsDate%') this does not return a sql error, however it makes my query limit the same as the date and the single quote is removed after the % sign in the sql printout.
oddly if i reverse and put the percent sign in front of $setsDate (%setsDate) is cancels out everything after the % and shows everything.
any help would be appreciated.
UPDATED 9:35 EST 03/10
Here is the sql output ('%s %%'):
SELECT * FROM media_set AS f INNER JOIN media_set_sets_assoc AS fs ON fs.set_id = f.set_id AND fs.sets_id = '1' WHERE f.posted LIKE '201312 %' AND f.is_active = 1 ORDER BY f.set_id DESC LIMIT 0, 18
Here is SQL output ('%s%%'):
WHERE f.posted LIKE '201312%'
Notice no space between.
I believe you should be escaping the percentage sign for use in a LIKE statement, as such:
WHERE f.posted LIKE '%s %%'
Your problem is that sprintf treats % as a special character, so it gets confused when you want an actual % character. The solution for that is to use %% when you want the actual % character.
However, please do not insert values into your SQL with sprintf. That is an extremely bad practice and it is responsible for most of the security vulnerabilities in PHP code. Escaping your strings is not good enough. Use parameterized queries instead.
You should use the PDO or mysqli extensions, which support parameterized queries.
There are many articles explaining why you should not splice values into your SQL. Here is one: http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
The way you should be doing it is discussed here: https://stackoverflow.com/a/60496/219155

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);

Alternative to heredoc, for continuation from the next line for php code, like it is slash in c language?

I have a long query
$s = $dbh->prepare("SELECT name,type,
(select count(opinionid) from fe_opinion where actor=name) as countopinion,
(select count(commentid) from fe_comment where actor=name) as countcomment,
(select count(commentid) from fe_reply where actor=name and replyto<>null) as countreply,
(select count(voteid) from fe_vote where actor=name and replyto<>null) as countvote,
(select count(voteid) from fe_vote where actor=name and replyto<>null and vote=1) as countagree,
(select count(voteid) from fe_vote where actor=name and replyto<>null and vote=0) as countdisagree
from fs_actor where name=:name");
and It gives me a syntax error when I write it like this in multi line. I am unsure about the compiler because i didnt execute it. Is it supposed to work in this format or should I use heredoc?
How can I continue writing a string from next line? Should ı do it by continuing to next lineby pressing enter? Should I use heredoc or Is there a special new line character?
I've found this example in phpdoc
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
so now I think my syntax error is something else.
Just a shot in the dark here, are you sure it's not that last comma after countdisagree that's giving you a syntax error? You don't put a comma after the last part of the SELECT, and you might not have realized you put it there, I know I've done that quite a bit myself when breaking up a long SQL query, and it will give a syntax error if it's there because it's expecting another statement to select from.
SQL queries, multiline or otherwise, should only give a syntax error if there actually is one, so if you get a syntax error, you can bet that you have one. You could break that up so you only have one word on each line and it won't give a syntax error.
There's no line-continuation character in PHP. You should use Heredoc:
$s = $dbh->prepare(<<<'EOQ'
SELECT name, type,
(SELECT COUNT(opinionid) FROM fe_opinion WHERE actor = name) AS countopinion,
(SELECT COUNT(commentid) FROM fe_comment WHERE actor = name) AS countcomment,
# ...
FROM fs_actor WHERE name = :name"
EOQ
);
The single-quotes around EOQ here are what PHP inexplicably calls "Nowdoc" syntax, which is the same as Heredoc but isn't parsed--the equivalent of using $s = 'Hello $world'; vs. double-quoted $s = "Hello $world";--which might save you a couple milliseconds somewhere down the line (but, incidentally, seems to throw off SO's syntax highlighting).
Your only (reasonable) alternative in PHP--other than storing your queries elsewhere--is to use string concatenation, which gets pretty ugly:
$s = $dbh->prepare(
'SELECT name, type, ' .
' (SELECT COUNT(opinionid) FROM fe_opinion WHERE actor = name) AS countopinion, ' .
' (SELECT COUNT(commentid) FROM fe_comment WHERE actor = name) AS countcomment, ' .
// ...
' FROM fs_actor WHERE name = :name'
);
...which is pretty ugly and requires you to mind your spaces.

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

Query that works in SQL but not in PHP

I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL, but when I use it within my PHP script it says "Error in Query" then recites the entire SQL statement. If I copy and paste the SQL statement from the error message directly into MySQL it runs with no errors.
From my research I believe I am missing an apostrophe somewhere, so PHP may be confusing the clauses, but I am not experienced enough to know where to insert them.
The query is using a variable called $userid which is specified earlier in the PHP script.
$sql= <<<END
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_B.seller, Table_B.final_price
FROM Table_A
INNER JOIN Table_B ON Table_A.id=Table_B.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
UNION ALL
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_C.seller, Table_C.final_price
FROM Table_A
INNER JOIN Table_C ON Table_A.id=Table_C.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
END;
After this section the script then goes on to define the output and echo the necessary pieces as per usual. I'm happy with the last part of the code as it works elsewhere, but the problem I am having appears to be within the section above.
Can anyone spot the error?
Edited to add the following additional information:
All of the fields are numerical values, none are text. I have tried putting '$userid' but this only makes the error display the ' ' around this value within the error results. The issue remains the same. Adding parenthasis has also not helped. I had done a bit of trial and erorr before posting my question.
If it helps, the last part of the code bieng used is as follows:
$result = mysql_query($sql);
if (!$res) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
$total_bought = 0;
while ($row = mysql_fetch_array($result)) {
$total_bought += $row[0];
}
$total_bought = number_format($total_bought, 0);
echo '<b>Your purchases: ' . $total_bought . '</b>';
echo "<b> gold</b>";
You're checking !$res, it should be !$result:
$result = mysql_query($sql);
if (!$result) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
I suppose, you're echo()ing the query somewhere and copy-pasting it from the browser. Could it be that the $userid contains xml tags? They wouldn't be displayed in the browser, you would have to view the page source to spot them.
you should test with $userid quoted, and parentheses around the two statements.
I'm assuming that rated_user_id is a numeric field, but what type is seller? If it's a character field, then $userid would have to be quoted as streetpc suggests.
Another thing to check is that you have at least one space after the end of your lines for each line of the query. That has tripped me up before. Sometimes when going from your editor/IDE to the database tool those problems are silently taken care of.

Categories