When running my PHP script It keeps giving me the error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
This is my sql code I have other than selecting from the table. I have commented out all of this and not gotten an error, so I'm assuming its occuring in this block of code.
if($status === 1){
$sqlQ = mysql_query("UPDATE tablename SET status=1 WHERE steam64='$id'");
if(!mysql_query($sqlQ, $con)){
die('Error: ' . mysql_error());
}
}else if($status !== 1){
$sqlQ = mysql_query("UPDATE tablename SET status=2 WHERE steam64='$id'");
if(!mysql_query($sqlQ, $con)){
die('Error: ' . mysql_error());
}
}
What is really confusing me is the line 1 part.
You're violating the DRY principle big time. Why not something like...
$statusValue = ($status === 1) ? 1 : 2;
$sqlQuery = mysql_query("UPDATE `14d2_group` SET `status` = $statusValue WHERE `steam64` = '$id'"):
UPDATE 2: It looks like there's a need for additional clarification.
mysql_query function doesn't only create a query: it actually sends in to MySQL - and returns the result. In case of UPDATE it will return FALSE if query has failed. That's why you shouldn't call mysql_query twice, as you did in the original example.
You can check how many lines were actually updated with mysql_affected_rows function.
UPDATE 3: Finally get it. ) That was the reason error appeared: you tried to call mysql_query with result of the last update query. Which was, as TRUE converted to String, just '1'. )
You're using the result from one query as a query itself.
What you probably wanted to do is:
if($status === 1){
$sqlQ = mysql_query("UPDATE tablename SET status=1 WHERE steam64='$id'");
if (!$sqlQ) {
die('Error: ' . mysql_error());
}
}
else {// no need for your if-statement here because it would always be true
$sqlQ = mysql_query("UPDATE tablename SET status=2 WHERE steam64='$id'");
if(!$sqlQ){
die('Error: ' . mysql_error());
}
}
"Line 1" corresponds to line 1 of the query, not the script invoking it. To add the line of the script invoking it, use:
die('Error: ' . mysql_error() . ' in ' . $_SERVER['PHP_SELF'] . ' on line ' . __LINE__ );
As for the query, I don't really see anything jumping out at me. The only suggestion I have right now is to always enclose field names in backticks, just in case they're keywords (it also makes them clearer to read)
Also, your else if is redundant. If $status === 1 doesn't run, then clearly $status !== 1 must be true.
Because of type casting, status=1 is not a problem. I'm assuming $id has some probrem. Once change $id to other safe value (1, 'foo'...) then check it works or not.
The 'line 1' part is SQL saying that hte message it recieved had an error on line 1 -- the first line of the command that SQL tried to process.
If I had to make a guess, status isn't set to a number type, so you need to put quotes around it so that SQL knows it's being passed a variable.
Edit: OK, the other solution might be right too. We both made different assumptions about your data structure, and I think his is better. Try it first.
Related
I am beginner and I am trying update tables in Joomla (3.8) database and I get 504 Gateway Time-out nginx error at the following sql query:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$condition = array(
$db->quoteName('B.virtuemart_product_id') . ' >= '.$product_id_from,
$db->quoteName('B.virtuemart_product_id') . ' <= '.$product_id_to);
$query->select(array('B.virtuemart_product_id, A.product_sku,
A.price_CZK, A.price_EUR'))
->from($db->quoteName('#__watrex_price_list_temp', 'A'))
->join('INNER' , $db->quoteName('#__virtuemart_products', 'B') . '
ON (' . $db->quoteName('B.product_sku') . ' = ' . $db-
>quoteName('A.product_sku') . ')')
->where($condition,'AND');
$db->setQuery($query);
$num_rows = $db->getNumRows();
$results = $db->loadObjectList();
...
Result can contain up to 50000 items. How can I fix this problem? Thank you
I suspect that getNumRows() is the culprit here. When I run call echo $db->getNumRows() on my localhost with a successful query returning a non-empty result set to replicate the issue, I get:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp64\www\blah\libraries\joomla\database\driver\mysqli.php on line ###
NULL
To fix this, add $db->execute(); on the line before $db->getNumRows() and everything works happily and as desired. That said, I recommend just calling count() or sizeof() on $results because you'll get the same output without having to add the execute() call.
If that isn't the cause, this may or may not be within your control. You may wish to work through this checklist of advice: https://www.lifewire.com/504-gateway-timeout-error-explained-2622941
As for how to process your result set with less memory consumption, you might entertain James Garrett's suggestion.
As for subtle refinements to your query:
Your SELECT clause renders appropriately, but the syntax seems to be designed with the intent to create an array of columns. Truth is, you have a single-element array containing all four columns. This only becomes problematic if you decide to apply quoteName() to the array.
I recommend lowercase table aliases so that they do not "catch the eye" as MySQL keywords. SQL Queries - Paragraph 1
The ON declaration doesn't need to be parenthetically wrapped.
None of your tables or columns actually need quoteName() to be called on them to maintain stability/security. You may choose to omit them to make your code easier to read, but the Joomla coding standards demand 100% employment of the call (I personally dislike this stance). SQL Queries - Paragraph 5
Table names and table column names should always be enclosed in the quoteName() method to escape the table name and table columns.
It may not aid in performance, but BETWEEN is "inclusive" and is specifically designed to do what your two WHERE conditions require. https://www.techonthenet.com/mysql/between.php
My recommended snippet:
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(["b.virtuemart_product_id", "a.product_sku", "a.price_CZK", "a.price_EUR"]))
->from($db->quoteName("#__watrex_price_list_temp", "a"))
->innerJoin($db->quoteName("#__virtuemart_products", "b") . " ON " . $db->quoteName('b.product_sku') . " = " . $db>quoteName("a.product_sku"))
->where($db->quoteName("b.virtuemart_product_id") . " BETWEEN " . (int)$product_id_from . " AND " . (int)$product_id_to);
$db->setQuery($query);
if (!$results = $db->loadObjectList()) {
echo "No Rows";
} else {
// if you need to know the count...
echo count($results);
// iterate the result set
foreach ($results as $row) {
// ... yatta-yatta ...
}
}
If ALL of the above fails, I recommend a re-think of your project. Perhaps you should be reducing the result set volume with LIMIT and using pagination techniques if necessary.
p.s. Rick James has some excellent advice about adding indexes.
I've been trying to make this code work for hours now but I can't seem to find solution. I've serached all relevant topics and tried to change the code, punctuation etc. but none of them worked for me.
The result is always "Success!" but the database update never works (checked in phpmyadmin).
I hope that you can find the error. The code is the following:
if(empty($_POST['nev']) || empty($_POST['orszag']) || empty($_POST['telefonszam']) || empty($_POST['iranyitoszam'])
|| empty($_POST['megye']) || empty($_POST['varos']) || empty($_POST['utca'])) {
echo "Failure! Missing data...";
}
else {
$nev = mysql_real_escape_string($_POST['nev']);
$orszag = mysql_real_escape_string($_POST['orszag']);
$telefonszamm = mysql_real_escape_string($_POST['telefonszam']);
$iranyitoszam = mysql_real_escape_string($_POST['iranyitoszam']);
$megye = mysql_real_escape_string($_POST['megye']);
$varos = mysql_real_escape_string($_POST['varos']);
$utca = mysql_real_escape_string($_POST['utca']);
$shipping_query = mysql_query("UPDATE users
SET Name=".$nev.", Phone=".$telefonszam.",
Country=".$orszag.", State=".$megye.",
City=".$varos.", ZIP=".$iranyitoszam.",
Road=".$utca."
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
echo "Success!";
}
Thank you for your help!
You're missing quotes around the strings in your query.
$shipping_query = mysql_query("UPDATE users
SET Name='".$nev."', Phone='".$telefonszam."',
Country='".$orszag."', State='".$megye."',
City='".$varos."', ZIP='".$iranyitoszam."',
Road='".$utca."'
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
You also no error checking on your query. So whether it succeeds or fails it will always say, "success". You need to check to see if there is a MySQL error ir rows updated before you can declare success.
Name, Phone, Country etc etc seam like VARCHARs. so, it should be treated as a string.
So, query should be like.
"UPDATE users SET Name='".$nev."', Phone='".$telefonszam."',Country='".$orszag."', State='".$megye."',City='".$varos."', ZIP='".$iranyitoszam."',Road='".$utca."' WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'"
As other answers have pointed out, you're missing quotes around your string variables.
When you're MySQL queries are failing to execute, try echoing your queries while debugging to see what exactly you're sending to the database.
$myValue = "Green";
$mySQL = "UPDATE MyTable SET MyColor = " . $myValue;
$myQuery = mysql_query($mySQL);
echo $mySQL;
Spotting the error visually is much easier when the entire SQL string is assembled in one piece.
You can also copy the assembled SQL string and paste it straight into a phpmyadmin query to get debugging information from it.
I have always struggled with a fairly basic concept in my PHP INSERT/UPDATE code. Should I always be checking for the number of affected rows after every INSERT/UPDATE because in the vast majority of times I am only ever performing one INSERT/UPDATE and it seems to cause more problems than it fixes by checking that only one row was affected.
Below is my standard code to perform the INSERT/UPDATE and this code fails if the user is updating a record without changing anything because the affected rows will be 0. I could write code to check that at least one field has changed but on large forms this seems very clunky and was wondering if it is really worth it because I have never really ever caught any errors by checking this number anyway.
<?php
$whereSql = '';
$groupSql = 'INSERT INTO';
if(isset($_POST['id']) && is_numeric($_POST['id'])){
$groupSql = 'UPDATE';
$whereSql = 'WHERE id = ' . $_POST['id'];
}
$groupSql .= ' sometable SET name="' . $name . '" ' . $whereSql;
$groupDb = mysqli_query($groupSql, $dbObject) or die("Login DB error:".mysql_error());
if(mysqli_affected_rows($dbObject) == 1){
//redirect
}else{
die('System Error');
}
You should be checking return values on queries. A select/update query which affects/returns no rows is NOT an error condition, it's simply an empty result set, or an update which happened to affect nothing.
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Consider a user signup system which checks for the existence of a matching username:
SELECT id FROM users WHERE username='foo';
if the user foo does not exist, your system will barf and claim an error occurred. But an empty result set is NOT an error. It simply means the username is available for user.
Same for a system that handles grades:
UPDATE students SET failed=true WHERE score < 50;
getting 0 affected rows is NOT a failure. It just means all the students passed.
I would recommend checking if the query has failed, and if not, then if there was more than one row affected.
$groupDb = mysql_query($groupSql, $dbObject);
if (false === $groupDb) {
die("Login DB error:".mysql_error())
if (mysql_affected_rows($dbObject) > 1) {
die('System Error: failed to ' . $action . ' a document Group');
} else {
//redirect
}
This way you will redirect only in case of successful queries and if there was less than 2 rows affected (if that is important to you).
I am working on a website where an administrator can edit a schedule that they already created. They can click on any item on the schedule to edit it. For example, they can click on the shift start time and then it directs them to a page where they can update the value.
Unfortunately, I have not been able to get this to work for every value. It seems to be that the text values are working just fine, but I am getting a syntax error when it is a number.
Here is what I am using to update:
$type = $_GET['type'];
$value = $_GET['value'];
$week = $_GET['week'];
$newval = $_POST['newval'];
if(strlen($newval) > 0)
{
include '../dbinfo.php';
$type = $mysqli->real_escape_string($_POST['type']);
$week = $mysqli->real_escape_string($_POST['week']);
$tablename = $mysqli->real_escape_string("cs" . $_SESSION['squadron']);
$newval = $mysqli->real_escape_string($newval);
if((is_numeric($newval)))
{
$sql = "UPDATE $tablename SET $type=$newval WHERE week=$week";
}
else
{
$sql = "UPDATE $tablename SET $type='$newval' WHERE week=$week";
}
if($result = $mysqli->query($sql))
{
echo "Your specififed changed was completed successfully!<br>";
echo "<a href='edit.php?week=" . $week . "'>Continue editing</a>";
}
else
{
echo mysqli_error($result);
}
}
Changing a string results in the sql statement:
UPDATE cs14 SET shift_1_name='Test' WHERE week=1 (this works)
Changing a number results in the sql statement:
UPDATE cs14 SET shift_ 1_starttime=940 WHERE week=1 (this doesn't work)
It is giving me the MySQL error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1_starttime=940 WHERE week=1' at line 1
I have already researched this error, and I have checked the syntax over and over again. It doesn't work in phpmyadmin either. I have no idea what to check next!
Can anyone help me out with my syntax here??? Thanks!
At the numeric update query put quotes around,
$sql = "UPDATE $tablename SET $type='$newval' WHERE week='$week'";
The $type variable contains a space. Remove the space from it.
More specifically "shift_ 1_starttime" contains a space. Wherever your setting $type to "shift_ 1_starttime" remove the space from it. Or if thats how it is defined in the database surround it with backticks `
$sql = "UPDATE $tablename SET `$type`='$newval' WHERE week=$week";
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.