Error unterminated string literal when using php mysql? - php

I have a this code:
$sql = "SELECT * FROM news order by id DESC LIMIT 10";
$data = array();
$query = mysql_query($sql);
if(!$query) {
echo "Error: " . mysql_error();
exit;
}
while($row = mysql_fetch_object($query)) {
$data[] = $row;
}
return $data;
When I run code, result OK, But when I repair limit from 10 to limit 15 or more is error is unterminated string literal
$sql = "SELECT * FROM news order by id DESC LIMIT 15"; // limit 15, 20 or more

Really? I don't mean to sound condescending but are you absolutely sure that you're not overwriting the " when you change that 10 to a 15?
Because there nothing in that code that indicates unbalanced quotes. Failing that, there may be a problem earlier on in the code (though, of course, we can't see it).
I would suggest you cut and paste the exact code that's causing the problems.

This the type of error you need to separate from your main code base.
create a simple test php script that connects to the database and executes the query.
does that work? if not, create a small sample database and test on that.
if that fails, then post the create table statement along with insert statements. also post your code. odds are you're doing something else in the main code base that is causing the error.
if your sample code does work and your main codebase does, then you have to trace through your main code base and find out what you're doing wrong.

Related

Loop or Query causing Internal Server Error

Heres the story,
I am uploading a list of part numbers on text file via gzip, the reading is successful.
The format is:
"DATE"|"TYPE"|"ID"|"FPN"|"PN"|"IOC"|"FIELD"|"OVAL"|"NVAL"
Sample Value :
"2013-09-10 19:19:08"|"DU"|"10161000001354"|""|"ANTX100P001B24003"|""|"Sub-Category 1"|"Metal Antenna"|"PCB Antenna"
Now the scenario is, I loop on each entry to insert it to database and set notifications for users to see an update about that certain part number and get their email to conduct a mailing later in other page.
the loop code is here :
for($x=1;$x<=count($lines)-1;$x++){
$cur_row = trim(str_replace('"','',$lines[$x]));
$cols = preg_split('/\|/',$cur_row);
$query = sprintf('INSERT INTO `notification_details`(`NDATE`, `NTYP`,`NPID`,`NFPN`,`NPN`,`NIOC`, `NFILD`, `NOV`, `NNV`) VALUES(\'%s\',\'%s\',%s,\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')',$cols[0],$cols[1],$cols[2],$cols[3],$cols[4],$cols[5],$cols[6],$cols[7],$cols[8]);
mysql_query($query);
$query = 'SELECT DISTINCT `id` FROM `project_details` WHERE `prod_id` = \''.$cols[2].'\';';
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count>0){
$query = 'SELECT MAX(`NID`) FROM `notification_details`';
$result = mysql_query($query);
$row=mysql_fetch_array($result);
$NID = $row[0];
$query = sprintf('INSERT INTO `read_details`(`NID`, `PID`,`ISREAD`) VALUES(%s,%s,1);',$NID,$row['id']);
mysql_query($query);
}
echo $cols[2].".... Done!<br />";
flush();ob_flush();
}
//EMAIL LISTING BLOCK
echo "Listing E-mails...<br />";
$query = 'SELECT B.`proj_user`, C.`email` '
.'FROM `read_details` A, `project_details` B, `login_details` C'
.'WHERE A.`ISREAD` = 1 '
.'AND A.`PID` = B.`id` AND B.`proj_user` = C.`username` '
.'GROUP BY B.`proj_user`';
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
mysql_query('INSERT INTO `email_details`(`email`,`user`) VALUES(\''.$row[1].'\',\''.$row[0].'\')');
echo $row[1].".... Added!<br />";
}
Heres some runs I did:
Product (193 lines) + full run of the code above = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page
Product (193 lines) + less the Email Block = Successfull
Product (18,000 lines) + full run of the code above = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page.
Product (18,000 lines) + less the Email Block = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page.
I don't know if it just me or what, but even the server returns internal server error, the products are keep adding on the database (I look at it and try to query a count and it increments) and stops at random point, that point the site is become accessible again. But sometime it doesnt do that.
Any ideas? Thanks in advance.
EDIT :
NID & PID is BIGINT, ISREAD is BOOLEAN, the rest are LONGTEXT
Plus while running, the page is /uploadpcn.php, this code is under /do_upload_pcn.php
so the scenario is that, the whole process is in loading while on /uploadpcn.php and when the process ends, the browser will go to /do_upload_pcn.php showing all echos OR shows internal server errors anytime in the process.
Try to log the loop with each record and you may come to know which particular record is causing the error. You may also apply some try-catch logic. I presume this could be a parsing error.
Another thing to notice is that your first INSERT query does not contains single-quotes around the string data. This could be another issue leading to the error.
Edit:
This query in the code in the question $query = sprintf('INSERT INTOread_details(NID,PID,ISREAD) VALUES(%s,%s,1);',$NID,$row['id']); should be like:
$query = sprintf('INSERT INTO `read_details` (`NID`, `PID`, `ISREAD`) VALUES (\'%s\', \'%s\', 1);', $NID, $row['id']);
I would suggest to use double quotes for constructing queries so that you may easily use single quotes for parameters.

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

MySQL Delete Item from Table not working

I am trying to delete a record in my db based on the unique id ($id). Is there something wrong with this code? Probably a simple one for you php pro's.
function delAccount(){
mysql_query("DELETE FROM accounts WHERE id=".$id."LIMIT 1");
}
I get a :
Fatal error: Can't use function return value in write context in
/home/content/53/7311353/html/cca/accounts/include/processAct.php on line 15
My Class that I have powering everything:
class Accounts
{
function Accounts(){
if (isset($_POST['addacct'])){
$this->addAccount();
}elseif(isset($_POST['editacct'])){
$this->editAccount();
}elseif(isset($_POST['delacct'])){
$this->delAccount();
}else{
// redirect if loaded without a POST value set
header("Location: ../index.php?o=illegal&t=nodata");
}
}
You should, first of all, put a space between ".$id." and LIMIT so:
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
Secondly, the $id is NOT available within this function by default. Either do this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
and use delAccount($id_parameter); in your script to send the ID along with the function. Or try this:
function delAccount() {
global $id;
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
then you can call this function after you set the value of $id somewhere else in your code.
First: is the value for $id actually an id in the database? Second you need a space before "LIMIT", ie:
" LIMIT 1".
Are you sure $id is set?
If $id should be sent to the function as an argument, try this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=" . $id . " LIMIT 1");
}
EDIT: You missed a space character between the ID and the LIMIT.
Added some small improvements to the form of the query string:
function delAccount($id) {
mysql_query("DELETE FROM `accounts` WHERE `id` = " . $id . " LIMIT 1");
}
EDIT:
The error you get doesn't come from MySQL itself. Have you checked the returned value. It might return another error, or the returned value might be correct, but used in an erroneous way in later code.
Your error is from the PHP compiler. Are you doing something like this on line 15:
if (delAccount(...) = false) { ... }
? If so, change to ==.
Some hints on how to debug stuff like this.
If you suspect something is wrong, the first thing to do is to output the generated query. Like so:
$query = "DELETE FROM accounts WHERE id=".$id."LIMIT 1";
echo $query; // for debugging
That will show you that at least one thing is wrong with your query: You have a space missing before LIMIT.
mysql_query() returns false if it encounters an error. You can check for that, and output it using mysql_error(). Like so:
$result = mysql_query($query);
if(!$result) trigger_error("Database error!: ".mysql_error());
If $id comes from outside, like the $_GET array, make sure you have tested whether it is an integer before using it in a query to avoid SQL injection.

MYSQL syntax error

HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}

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