SQL row update +1 - php

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.

Related

Running a MySQL query using a string in php

Answer found (syntax): The column name of my string had to be encased in backticks " ` " as they contained spaces. Note that this means that the majority of this post has no relevance to the issue. The code has been corrected in case someone wants to do something similar.
So, I am doing a foreach loop to assign a value (1/0) to non-static columns in my database (it needs to support addition/deletion/editing of columns). I am using $connectionvar->query($queryvar); to do my queries which worked fine up until now when I'm trying to use a custom built string as $queryvar in order to change the column name to a variable within the loop. I've been outputting this string through echo and it looks exactly like my functional queries but somehow doesn't run. I've attempted to use eval() to solve this but to no avail (I feel safe using eval() as the user input is radio buttons).
Here's the loop as well as my thought processes behind the code. If something seems incoherent or just plain stupid, refer to my username.
foreach($rdb as $x) { //$rdb is a variable retrieved from $_POST earlier in the code.
$pieces = explode("qqqppp", $x); //Splits the string in two (column name and value) (this is a workaround to radio buttons only sending 1 value)
$qualname = $pieces[0]; //Column name from exploded string
$qualbool = $pieces[1]; //desired row value from exploded string
$sql = 'UPDATE users SET '; //building the query string
$sql .= '`$qualname`';
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\''; //$profilename is retrieved earlier to keep track of the profile I am editing.
eval("\$sql = \"$sql\";"); //This fills out the variables in the above string.
$conn->query($sql); //Runs the query (works)
echo ' '.$sql.' <br>'; //echoes the query strings on my page, they have the exact same output format as my regular queries have.
}
}}
Here's an example of what the echo of the string looks like:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
For comparison, echoing a similar (working) query variable outside of this loop (for static columns) looks like this:
UPDATE users SET profiletext='qqq' WHERE username='Admin2'
As you can see the string format is definitely as planned, yet somehow doesn't execute. What am I doing wrong?
PS. Yes I did research this to death before posting it, as I have hundreds of other issues since I started web developing a month ago. Somehow this one has left me stumped though, perhaps due to it being a god awful hack that nobody would even consider in the first place.
You need to use backticks when referring to column names which have spaces in them. So your first query from the loop is outputting as this:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
But it should be this:
UPDATE users SET `Example Qualification 3`='1' WHERE username='Admin2'
Change your PHP code to this:
$sql = 'UPDATE users SET `'; // I added an opening backtick around the column name
$sql .= '$qualname`'; // I added a closing backtick around the column name
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\'';
Example Qualification 3 : Is that the name of your Mysql Column name ?
You shouldnt use spaces nor upper / lower case in your columnname.
Prefere : example_qualification_3
EDIT :
To get column name and Comment
SHOW FULL COLUMNS FROM users

Stop quotes from being escaped in zend where

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,"'"));

PHP - SQL Query failure, seems valid?

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]}'

UPDATE in mysql didn't work in my PHP page.

First of all I'm a rookie to Programming, I created a PHP page to update a value from my mysql(myadmin) database, but the value is not updating. I also tried to retrieve values from database it's working just fine but this UPDATE code is not working! I don't know why, please check out my code below.
$qs=mysql_query("update staff set review=$newrate where name=$rateuser");
$resu=mysql_query($qs);
All variables are double defined, assigned with proper values, checked and I tested variables using echo, table name is also checked, it's all fine, but I think the problem is with Update query, I searched internet for the syntax but it's not different than mine. Please help me out
How are $newrate and $rateuser set?
mysql_query("UPDATE staff SET review = '".mysql_real_escape_string($newrate)."' WHERE name = '".mysql_real_escape_string($rateuser) ."'");
http://php.net/manual/en/function.mysql-real-escape-string.php
Try:
$qs=mysql_query("update staff set review='$newrate' where name='$rateuser'");
Do not use second line.
You probably just need some " around your values $newrate and $rateuser
But if you did an echo, why not actually echo for us what the query-string becomes?
You need single quotes around string values on your query:
$qs=mysql_query("update staff set review='$newrate' where name='$rateuser'");
(assuming both variables are strings)

Help me debug my SQL INSERT, please?

I am pulling back some data from the twitter query API, and parsing it through PHP like so:
$i =0;
foreach ($tweetArray->results as $tweet) {
$timeStamp = strtotime($tweet->created_at);
$tweetDateTime = date('m-d-Y H:m:s', $timeStamp);
if($i > 0){
$SQL .= ',';
}
$SQL .= "(". $tweet->id .",'" . $tweet->from_user ."','". addslashes($tweet->profile_image_url) . "','". addslashes($tweet->text). "','" . $tweetDateTime ."')";
$i++;
}
$SQL .= " ON DUPLICATE KEY UPDATE 1=1";
This leaves me with a SQL statement looking like this:
INSERT
INTO
tblTwitterSubmit (tweetId, twitterAuthor, authorAvatar, tweetText, tweetDateTime)
VALUES
(111,'name','http://url.com','a string of text','03-04-2011 13:03:09'),
(222,'anothername','http://url.com','another tweet','03-04-2011 12:03:51')
ON DUPLICATE KEY UPDATE 1=1;
I am unfortunately getting the following 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=1' at line 1.
Edit:
The 1=1 is supposed to not do anything. The tweets don't change, and so if I pull the same one back twice for any reason, nothing will happen, but it also won't throw a duplicate key error.
Re-edit:
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just make a bunch of submissions instead of one long sql string.
Hopefully this is better practice.
Leaving this open for a couple minutes hoping for some feedback if this is the way to do it or not.
The ON DUPLICATE KEY UPDATE requires a column name, something like this, assuming tweetId is the key column that's getting duplicates.
ON DUPLICATE KEY UPDATE tweetId=tweetId+1
Your 1=1 doesn't actually do anything.
Are you sure you're using the right syntax for on duplicate key update ?
Judging from it's manual's page, it seems you have to specify a column name, and not 1=1.
From what I understand, if you want to indicate "use the value from the values() clause when there's a duplicate", you should use something like this :
on duplicate key update your_col=values(your_col)
Quoting the relevant part :
You can use the VALUES(col_name)
function in the UPDATE clause to
refer to column values from the
INSERT portion of the INSERT ... ON
DUPLICATE KEY UPDATE statement.
In other words,
VALUES(col_name) in the ON
DUPLICATE KEY UPDATE clause refers to
the value of col_name that would be
inserted, had no duplicate-key
conflict occurred. This
function is especially useful in
multiple-row inserts.
Then, as a sidenote, you must escape your strings using the function that matches your API -- probably mysql_real_escape_string -- and not the generic addslashes, which doesn't know about the specificities of your database engine.
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just

Categories