Update Else Insert MySQL query - mysql

Hello i was here yesterday with this problem, i don't really know how to use this site well as i am new so i reposted. but I'm getting an error with this block of code and i think its the Update query which contains a syntax error.
// Updates if player's record already exists
$result = mysql_query("UPDATE PlayerStat SET Position='$POS', Number='$NUM', Name='$PlyrName', Status='$Status', TDS='$TDS', INT='$INT', YDS='$YDS', RTG='$RTG', Team='$Team' WHERE Name='$PlyrName'");
echo mysql_error();
if (mysql_affected_rows()==0){
// Populates table if record is non existent
$result = mysql_query("INSERT INTO PlayerStat(`Position`, `Number`, `Name`, `Status`, `TDS`, `INT`, `YDS`, `RTG`, `Team`) VALUES ('$POS','$NUM','$PlyrName','$Status','$TDS','$INT','$YDS','$RTG','$Team')");
echo mysql_error();
}
The Error message
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 'INT='1', YDS='86', RTG='52.5', Team='ARI' WHERE Name='Bartel, Richard'' at line 1

INT is a keyword in mysql (declares and integer), if it's your column name you should surround it backticks (`) like so: `INT`.
It's good practice to put these in even though they're not necessary in all cases
UPDATE
PlayerStat
SET
`Position` = '$POS',
`Number` = '$NUM',
`Name` = '$PlyrName',
`Status` = '$Status',
`TDS` = '$TDS',
`INT` = '$INT',
`YDS` = '$YDS',
`RTG` = '$RTG',
`Team` = '$Team'
WHERE
`Name` = '$PlyrName'

Two things:
Check the manual for INSERT ... ON DUPLICATE KEY UPDATE which should do this in one statement.
I suggest you take a hard look at mysql_real_escape_string() or similar in PHP to escape your data and prevent SQL Injections.
If you don't know what SQL Injections are, then google it and spend a bit of time reading NOW before it's too late and some cracker or script kitty has your database.
Hope this helps!

You may want to check these websites.
http://www.w3schools.com/php/php_mysql_update.asp
http://www.tizag.com/mysqlTutorial/mysqlupdate.php
And you might also want to check your spelling mistake or the single quote or double quote. Other than that, check your database namings and data type.

Related

IF condition MySQL not working

I am trying to execute a query into MySQL but it keeps telling me i am using the wrong syntax, I tried searching the MySQL community but I am not getting anything usefull.. most of the answers i find on google are for other databases yet they label them for "MySQL", yet it keeps failing.
This is the statement i am trying to execute:
$statement = "IF (SELECT ttb_id FROM timetable WHERE ttb_week = $i AND ttb_time = $j) THEN
BEGIN
UPDATE types SET typ_name = '$subj'
WHERE typ_name = 'student';
END;
ELSE
BEGIN
INSERT INTO types VALUES (null,`Yo`);
END;
";
error:
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 'IF (SELECT ttb_id FROM timetable WHERE ttb_week = 0 AND ttb_time = 0) THEN ' at line 1
I am using:
PHP Script Language Version 5.2.6
MySQL Database Version 5.0.51b
I have been looking around but to no avail, and the if condition stated on the MySQL dev website are not helping at all..
I am new to this and it is driving me mad! all the different queries i tried failed.. it is never the right syntax.
I found many answers for the problem on stackExchange and other websites but it is always wrong.. also I remember this structure from a VB.net lesson a while ago so maybe this is for MSSQL? then what about MySQL? everyone so far listed similar structure and said it works for MySQL, I took my answer from an answer on this community* labeled for MySQL and he claimed it worked. this is one of many i tried.
I would really appreciate your help
*: Usage of MySQL's "IF EXISTS"
My first thought would be you're not comparing your SELECT return to anything to actually utilize your conditional logic. Are you just looking to see if your query returns values? If it doesn't return a value then you insert a new record in otherwise you update.
Maybe use IS NOT NULL or a check to see count on the select to see how many rows and compare to see if that's greater than 0.
IF (SELECT ttb_id FROM timetable WHERE ttb_week = $i AND ttb_time = $j IS NOT NULL) THEN
IF (SELECT COUNT(*) FROM timetable WHERE ttb_week = $i AND ttb_time = $j) > 0 THEN

mysql_result() expects parameter 1 to be resource, boolean given instead

if(mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'");
return true;
} else {
return false;
}
I know that this is probably a duplicate from somewhere, but this is driving me insane right now. Please help.
This error message is displayed when you have an error in your query which caused it to fail.
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);. If you have any syntax errors this will point them out to you.
Use mysql_error(). mysql_error() will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string() to escape your input.
Make sure you are not mixing mysqli_* and mysql_* functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*. See below for why.)
Other tips
mysql_* functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Your mysql_query() function call is failing and returning FALSE which is an invalid 1st parameter for mysql_result().
Run the mysql_query() separately and call mysql_error() to get the error.
The query is failing because COUNT (...) should be COUNT(...) otherwise it tries to find a column called count in the table.
Your query should read
SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0
Remove the space between COUNT and (user_id)

MySQL Syntax Error on complicated query

Sorry for the derp question (as I'm sure it probably is), but after going over the manual and through Stack Overflow for answer on this one, I'm still unsure of what's wrong with this database query.
Some info:
I'm trying to create a function that creates an array of all zipcodes within a radius around another zipcode. I'm using this as reference: http://www.movable-type.co.uk/scripts/latlong-db.html
I have actually had this string working on my live site, however I'm now redoing some work on my localhost (WAMP) which is running MySQL 5.5.24. The platform is Wordpress.
I understand that quotes (or a lack thereof) around database names, fields, etc and I've used several variations with no luck at all.
Anyways, enough talk. Here's 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 ''geo_data' WHERE 'Lat>44.566' AND 'Lat<44.566' AND 'Lon>-109.208' AND 'L' at line 4]
And here's the code:
SELECT 'Postcode', 'Lat', 'Lon', 'acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))*cos(radians(Lon)-$lon))*$R' AS D
FROM (
SELECT 'Postcode', 'Lat', 'Lon'
FROM 'geo_data'
WHERE 'Lat>$minLat' AND 'Lat<$maxLat'
AND 'Lon>$minLon' AND 'Lon<$maxLon'
)
AS 'firstcut'
WHERE 'acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))*cos(radians(Lon)-$lon))*$R' < '$rad'
ORDER BY 'D'
Thanks for the help, sorry again if I'm missing the obvious.
EDIT
Thanks guys! Got it working. Here's the working code for the benefit of others:
SELECT `Postcode`, `Lat`, `Lon`, acos(sin($lat)*sin(radians(`Lat`)) + cos($lat)*cos(radians(`Lat`))*cos(radians(`Lon`)-$lon))*$R AS `D`
FROM (
SELECT `Postcode`, `Lat`, `Lon`
FROM `geo_data`
WHERE `Lat`>'$minLat' AND `Lat`<'$maxLat'
AND `Lon`>'$minLon' AND `Lon`<'$maxLon'
)
AS `firstcut`
WHERE acos(sin($lat)*sin(radians(`Lat`)) + cos($lat)*cos(radians(`Lat`))*cos(radians(`Lon`)-$lon))*$R < '$rad'
ORDER BY `D`
You're using single quotes ' around your field and table names. This is incorrect. You want to use backticks `. Using quotes makes MySQL interpret it as a string.
You also have your conditions and calculations inside quotes, that just makes them into strings.
For example, your inner query should look like this:
SELECT `Postcode`, `Lat`, `Lon`
FROM `geo_data`
WHERE `Lat > '$minLat' AND `Lat` < '$maxLat'
AND `Lon`> '$minLon' AND `Lon` < '$maxLon'
'geo_data' is a string geo_data [with backticks (`)] is a tablename

Issues with simple insert statement

I am working on this code and i am using a simple insert statement and I cant figure out why its not working. If anyone could see what I am doing wrong please let me know. Thanks!
This is the error I am getting:
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 'long,comments)
VALUES (2 ,2012-11-18 21:25:30, 39.3436984, -76.5856958, hh)' at line 1
here is the code:
mysql_query ("INSERT INTO incidents (emergency_type,date_time,lat,long,comments)
VALUES (2 ,$catchDate, $catchLat, $catchLong, $catchDescription)") or die(mysql_error());
echo"<br /> Data inserted";
Long is a reserved word, try `long` surrounded with backticks instead.
Reference https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
A quick browse around the docs reveals that you should be investigating PDO::prepare and PDO::execute to do this. Your current method appears to be vulnerable to SQL injection.
I'm not a PHP programmer, but something like:
$db = get a db handle from somewhere
$st = $db->prepare('Insert Into Incidents (emergency_type, date_time, lat, `long`, comments) Values (?, ?, ?, ?, ?)');
$st->execute(array(2 ,$catchDate, $catchLat, $catchLong, $catchDescription));
LONG is a keyword/reserved word in mysql. You can use backticks to escape it
INSERT INTO incidents (emergency_type,date_time,lat,`long`,comments)
Or change your table column name to longitude
INSERT INTO incidents (emergency_type,date_time,lat,`long`,comments)
VALUES (2 ,$catchDate, $catchLat, $catchLong, '$catchDescription')
LONG is on the list of MySQL Reserved Keywords. Escape it with backtick instead.
One more thing, values for date_time and comments must be enclosed with single quotes as they are not numeric.
and you query is now vulnerable with SQL Injection, please take time t read the article below
How can I prevent SQL injection in PHP?

SQL query is correct but still a "SQL error 1064" appears

I can't deal with it. I'm experiencing big troubles with this very query:
UPDATE books
SET books.out = books.out + 1
WHERE id = 81813130;
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
If I run it on my phpMyAdmin, everything's fine and everything completes, but in my CakePHP application this query doesn't work and when I perform a debug this is what I'm told:
Warning (512): SQL Error: 1064: 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 'UPDATE books SET books.available = 0 WHERE books.in = books.out' at line 1**
I'm calling my query from a controller:
$this->Lending->update_lendings($this->data['Lending']['book_id']);
and the actual query is of course into the model:
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
";
I really can't say why this isn't working. It seems that error 1064 Mysql is a very common question in here but I didn't find anything useful about my very issue.
I steadfastly thank you for your support and help.
It looks like your problem might be due to PHP's lack of support for Multiple Statement Execution. Multiple Statement Execution allows you to run two queries in a single request and receive multiple result-sets in response.
MySQL DOES support it, but the default setup in PHP prevents this (that is, if you're using the deprecated mysql_connect() era functions). This is actually a nice default because there are some serious bugs that can be introduced by allowing multiple-queries (see SQL injection).
So, the solution could be to alter your code to request the data separately.
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";";
mysql_query($db, $query);
$query = "UPDATE books
SET books.available = 0
WHERE books.in = books.out;";
mysql_query($db, $query);
That being said, if you think that it's safe enough to use multi-statements (that is, if all of the input values are sanitized), then go ahead and try to use the mysqli functions (there not even deprecated!).
mysqli_multi_query( $query ) should give you the flexibility you need.
aparently, it's because you use reserved words in your query, try and escape all table names and table columns in ``
list of reserved words in mysql available here
If the second Update statement is meant to change only the row that the first statement updated, then you could use a single Update:
UPDATE books
SET out = out + 1
, available = CASE WHEN in = out
THEN 0
ELSE available
END
WHERE id = 81813130