I'm using XMLHttpRequests to call a PHP script on my server, but the query is continuously failing. I've rewritten it several times, am I going about this the wrong way? I've researched statements and seen them written in a very similar fashion.
$query = mysql_query("UPDATE arts SET a_id=((SELECT a_id FROM logs
WHERE unique='{$_GET['unique']}') + ',' + (SELECT id
FROM mf_arts WHERE art='{$_GET['url']}'))
WHERE unique='{$_GET['id']}'");
if(!$query)
{
$fquery = mysql_query("INSERT INTO mf_arts (art,name)
VALUES('{$_GET['url']}','{$_GET['name']}');
UPDATE mf_logs SET a_id=((SELECT a_id FROM mf_logs
WHERE unique='{$_GET['id']}') + ',' + (SELECT id FROM
mf_arts WHERE art='{$_GET['url']}'))
WHERE unique='{$_GET['id']}'");
if(!$fquery) echo("ADD IMPOSSIBRU");
} else echo "1";
I feel like I'm missing a very small, but very important portion. I tried using IF EXISTS originally but I keep encountering the same problem, so I tried to simplify it to a statement after statement sort of hierarchy. Honestly, thanks for any help. StackOverflow is great.
unique is a reserved word see: dev.mysql.com/doc/refman/5.5/en/reserved-words.html
either avoid it, best option or wrap it in back ticks
Multiple queries aren't allowed in mysql_query. After sanitizing your user input, try separating them
if(!$query)
{
mysql_query("INSERT INTO mf_arts (art,name)
VALUES('{$_GET['url']}','{$_GET['name']}')")
or die("ADD IMPOSSIBRU");
mysql_query("UPDATE mf_logs SET a_id=((SELECT a_id FROM mf_logs
WHERE `unique`='{$_GET['id']}') + ',' + (SELECT id FROM
mf_arts WHERE art='{$_GET['url']}'))
WHERE `unique`='{$_GET['id']}'")
or die("ADD IMPOSSIBRU - Update");
echo "1";
}
unique is a reserved keyword, as was explained above, use (``), like:
WHERE `unique`='{$_GET['unique']}'
Use INSERT INTO ... ON DUPLICATE KEY UPDATE ...
dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate
First, as has been mentioned previously, please please please sanitize your queries.
Second, within double quotes, don't use single quotes for array indices.
WHERE unique='{$_GET['unique']}'
should be
WHERE unique='{$_GET[unique]}'
Related
I have two tables, Requests & Accounting_Fundscenter_Request
I'm creating a SQL query in PHP that updates
Request_ID from Accounting_Fundscenter_Request WHERE ID is max
to
the max Request_ID from Requests
So far I have gotten the max(Request_ID) rom Requests, but I don't know how to take that value in php & sql and update the other Request_ID to equal that value.
Also, I cannot use the syntax "max(id)" because the "max" function will not work in my first query and I don't know why.
Here's what I have so far:
/* GET MAX ID FROM REQUESTS */
$selectMaxID = 'SELECT Request_ID FROM Requests ORDER BY Request_ID DESC LIMIT 1';
$maxIdResult = mysqli_query($conn, $selectMaxID); //run query
if (mysqli_num_rows($maxIdResult) > 0) {
while($maxid = mysqli_fetch_assoc($maxIdResult)) {
echo "Max Request ID: " . $maxid["Request_ID"]. "<br>";
} //echo result of
}
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxId);
This does not work. Is there a way to fix this or maybe do it in one query?
EDIT: with your help I found the solution:
You have many options here:
You can fix the syntax error you have in you insert query execution like this:
$insertFundsCenterMaxIdQuery = sprintf('INSERT INTO Accounting_Fundscenter_Request (Request_ID) VALUES (%d)', $maxid["Request_ID"]);
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxIdQuery);
This way you use string formatting to replace the variable instead of directly using $maxid["Request_ID"] in a string.
Please replace %d with %s in case the Request_ID is supposed to be string/varchar.
Or you can follow another approach and just use one query to do the work like this:
INSERT INTO Accounting_Fundscenter_Request (Request_ID)
SELECT MAX(Request_ID) FROM Requests
And just execute this query
You're facing a syntax error in the update query:
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
Using the double quotes in that variable hiding in the VALUES part, you are ending the string contained in insertFundsCenterMaxId. Following it is a raw string containing Request_ID which cannot be parsed by PHP. That's simply invalid code.
To solve it, you could start using prepared statements. They will also help you to secure your application against SQL injection.
There is also a solution to the syntax error problem alone - but that will leave your application vulnerable. That's why I haven't included a fix for that, but by checking how to build strings you might find it on your own. But please, please do not use it for this problem. Please.
I'm trying to add +1 in custom row. Example:
UPDATE `users` SET `MVP` = `MVP` + 1 WHERE `steam_id` = `%s`;
But nothing. What's wrong? Syntax looks good i think.
%s is a value so remove `
You can usually omit that everywhere unless you are using some "unlucky" column names
UPDATE `users` SET `MVP` = `MVP` + 1 WHERE `steam_id` = %s;
Take the ' away from the MVP you are incrementing.
UPDATE `users` SET `MVP` = MVP+1 WHERE `steam_id` = `%s`;
Post the entire code snipped. Can´t really help you like that. What is steam_id? What is %s. When do you replace it with an actual value? You should also just use prepared statements and not DYI that. %s is not how they look like in PDO or MYSQLI, but sure looks like a placeholder for a string.
You also marked this as insert, yet you´re doing an update.
Those `` are kinda unnecessary, never used them for column/table names, but appears to work at least in mysql console.
The sql snipped looks right, assuming MPV is numeric and the id is a string/varchar and equals %s, or you´re replacing it with something.
EDIT: As some have said the %s is the problem use nothing if it´s a int. Use single or double quotes if it´s a string. And you don´t need to use anything anywhere else, but if you wish to do so you can.
I have simple table of hashes with 3 columns . Id is an email address.
Now, I want to retrieve the hash given id and type.
I do this:
$select = $this->getDbTable()->select();
$select->where('id=?', $id)->where('type=?', $type);
And I get
SELECT "hashes".* FROM "hashes" WHERE (id=\'randomemail#randomurl.com\') AND (type=\'email\')
instead of
SELECT "hashes".* FROM "hashes" WHERE (id='randomemail#randomurl.com') AND (type='email')
I have played around with quote and quoteInto, but it keeps escaping the quotes. Everywhere I look, it seems this should not be happening. Where could I be going wrong?
The same query works if type and id are integers though [in which case there are no quotes required]
Thanks!
The problem with the query was with the code after the $select was created. Even though the quotes seem escaped, the select works fine when used with fetchAll or fetchRow.
The following snippet worked correctly,
$select = $this->getDbTable()->select();
$select->where('id=?', $id)->where('type=?', $type);;
$hash = $this->getDbTable()->fetchRow($select)->toArray();
even though $select->__toString() showed
SELECT "hashes".* FROM "hashes" WHERE (id=\'someemail#gmail.com\') AND (type=\'default\') LIMIT 1
Try this instead
select = $this->getDbTable()->select();
$select->where('id=?',trim($id,"'"))->where('type=?', trim($type,"'"));
i need to select the variable 'duration' from a database where the eventID equals $idnumber. Im using the query bellow but am not having any luck. Can anyone see any flaws.
$duration = mysql_query("SELECT `bs_reservations`.`duration`FROM bs_reservations WHERE (`bs_reservations`.`eventID` '$idnumber')");
Small change :
$duration = mysql_query("SELECT `bs_reservations`.`duration`FROM bs_reservations WHERE (`bs_reservations`.`eventID` = " . $idnumber . ")");
UPDATE :
$data = mysql_fetch_array($duration );
Try to print this $data......
I assume you're missing an = when comparing the 2 IDs at the end.
$duration = mysql_query("SELECT `bs_reservations`.`duration`FROM bs_reservations WHERE (`bs_reservations`.`eventID` = '$idnumber')");
Try this:
SELECT `bs_reservations`.`duration`
FROM `bs_reservations`
WHERE `bs_reservations`.`eventID` = '{$idnumber}'
I've added whitespace before the from, added an = before idnumber, added a backtick after the where and for good measure also added the { and } though they are not really needed, but good practice.
While the obvious problem is the missing operator "=" (most adequately answered by #Dave IMO), perhaps you're having difficulty using the data once the MySql query has been properly executed. One would think you could then take your variable "$duration" and use it. Not true. $duration is now a resource, and you need to extract the information from it. If you know you're only going to get one piece of data back, consider the following code after your query:
list($duration)=mysql_fetch_array($duration);
This of course resets $duration to the value retrieved by the query and is no longer usable as a mysql resource, but it gets what you're looking for.
If this was not your problem, my answer would be the same as #Dave
Edit: Sorry, after reviewing the questions and answers again, my answer would be as follows:
$duration=mysql_query("select `duration` from `bs_reservations` where `eventID`='$idnumber'");
My query below updates a record using variables to identify the data in the DB. I think my syntax is correct although it might be wrong. Also, I am absolutely sure that the variables have legitimate values in them. Why won't this query work?
UPDATE `databasename`.`".$tablename."` SET `stock` = '".$f."' WHERE `myerspark`.`item_id` ='".$g."' LIMIT 1
Thanks guys. Tom, yes I have tried that and it works fine. But it is frustrating because I echo all three variables at the end of the script and they all display legitimate values.
Hamish, how do I view these errors?
Jon_Darkstar, these variables are assigned in previous lines of code. Here is my entire code block:
//variables $f, $g, and $tablename assigned from POST variables in previous lines
mysql_select_db($database_Yoforia, $Yoforia);
mysql_query("UPDATE `yoforiainventory`.`".$tablename."` SET `stock` = '".$f."' WHERE `".$tablename."`.`item_id` ='".$g."' LIMIT 1 ");
mysql_close($Yoforia);
echo ($f);
echo ($tablename);
echo ($g);
Again, when i echo these variables, they all come out with good values.
I'm kind of confused what belongs to SQL, what belongs to PHP, where that string comes from, etc. What you have might be fine (if there is a double quote in front and end that i dont see.
I'd probably write it like this:
$sql = "UPDATE databasename.$tablename SET stock = '$f' WHERE myerspark.item_id = '$g' LIMIT 1"
$res = mysql_query($sql, $conn).....
you can backtick more stuff (and/or do mysql_real_escape) for 'extra safety;, but that covers the idea.
What is myerspark? i dont see how it relates to the query, that is probably you're real meaningful error, whether there is a syntax error or not. If myerspark is a seperate table from tablename then you've got an issue here, maybe a JOIN you ought to have?