I am trying to insert emails into a MYSQL table, and I am getting an 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 ' 19, 'blah#gmail.com')' at line 1
I've looked over the internet, and tried different combinations of collations and codes, but nothing will work. Is the '#' the problem here? I am getting this email address from decoding Facebook's JSON user object. Here are snippets from my code:
$user = json_decode(file_get_contents($jsonurl));
$userid = $user->id;
if($user->gender == "male") $usergender = TRUE;
else $usergender = FALSE;
$useremail = $user->email;
mysql_select_db("kirkstat", $con);
$result = mysql_query("INSERT INTO table (id, access, gender, age, email) VALUES ($userid, '$access_token', $usergender, 19, '$useremail')");
if (!$result){
echo("error.\n");
die('Invalid query: ' . mysql_error());
}
id is a bigint, access is a varchar, gender is a binary, age is an int, and email is a varchar.
Thanks for your help!
false casts as a string to an empty string. An empty string is not valid in SQL for an integer column (or a column value of any kind since it won't have a '' either).
Instead of false/true use 0/1.
# signs are fine in text. I believe it's your "gender" value that's probably causing the error -- you should echo out the full query.
Related
I have a page that updates the data of a specific user. The user has position, which is a foreign key. The query update (below) works fine without the position, but with the position I get the following error.
Query :
$queryUpdate = "UPDATE visitorsystem.employee SET idNumber = '$idNumber', name = '$name',
surname = '$surname',
position = 'SELECT positionid FROM visitorsystem.position WHERE positionName LIKE '%$position%'',
email = '$email'
WHERE employeeid = '$empId'";
$resultUpdate = mysqli_query($connection,$queryUpdate)
or die("Error in query: ". mysqli_error($connection));
Error in query: 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 'SELECT positionid FROM visitorsystem.position WHERE
positionName LIKE '%Informat' at line 3
I have tried to work my way around by using inner join as I have seen some solutions given here on stack but nothing has worked. Any Suggestions ?
Subqueries go within regular parens, not quotes, so in a general sense:
SELECT x FROM y WHERE z IN (SELECT z FROM a)
Single and double quotes (by default) are only for string values.
UPDATE
The SQL error I'm receiving is:
Error: SQLSTATE[42000]: Syntax error or access violation: 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 'WHERE (fb_id) = ('1018762834552473') ON DUPLICATE KEY UPDATE score='69139'' at line 1
I’m creating a leaderboard table for a Javascript game and I’m currently trying to insert the player’s score into my database whenever a certain Javascript function runs.
I’m doing this with an Ajax Post using Php. I’ve put a console.log into the success area of the Ajax, and it’s appearing, which I think means that the php file is running correctly, but the score isn’t being updated in the database, so I think that maybe there’s a mistake in my SQL code.
This is the Ajax Post:
$.ajax({
url: 'scripts/sendscore.php',
data: {'userid' : userid, 'score' : totalscore},
type: "POST",
success: function(response){
if (response.error) {
console.log('Score input error - ' + response.error.message);
}
else {
console.log("Score should be inputted correctly.");
}
}});
The leaderboard is for a Facebook game, so I’m sending two things in the Post, they are: the score, and the user’s id.
I want the php code to enter the score into the database where the user’s id that is sent matches the user’s id in the database, to simplify, I want it to insert/update the player’s score with the new score (a player shouldn’t have multiple scores in the database, they should only have one score). This is the SQL I’m using to try to achieve this:
<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO scoretable (score) VALUES(:score) WHERE (fb_id) = (:userid) ON DUPLICATE KEY UPDATE score=:score");
$stmt->bindParam(':userid', $userid);
$userid = $_POST['userid'];
$stmt->bindParam(':score', $score);
$score = $_POST['score'];
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
The database table is made up of two columns, like this:
scoretable
=========
fb_id
score
I’m getting the message “Score should be inputted correctly.” back in the console, so I think the problem might be with the line of SQL?
Any help with this would be really appreciated, thank you in advance!
Note that ON DUPLICATE KEY UPDATE checks every unique fields in table, not just PRIMARY key. You want ON DUPLICATE KEY to match a UNIQUE key for score, then your INSERT will work fine without the WHERE clause. The bad news is that Mysql does not allow where clause on duplicate key update, so a quick trick would be to use if statement:
Try this statement:
INSERT INTO `scoretable` (`score`) VALUES(:score)
ON DUPLICATE KEY UPDATE
`fb_id` = LAST_INSERT_ID(fb_id),
`score`= IF(VALUES(:score) >= score, VALUES(:score), score);
Here, fb_id is an auto-increment field that I do not want modified by the UPDATE; hence the LAST_INSERT_ID trick.
You are assigning values to variables $userid & $score after their binding.
Check the data type and size of the fb_id (may be it is not able to hold the value with the data type you have in the database 1018762834552473)
After doing some research I think I need the Output clause. Essentially I am taking the below SQL and inserting into the specified table when I receive the location of a file I am uploading to the server. When I upload into the table the ID is an auto increment field and the primary key.
$conn = mysqli_connect($DBHOSTmy, $DBuser, $DBpass, $DBmy) or die("An error occurred connecting to the database " . mysqli_error($conn));
$query = "INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.id, Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq VALUES ('" . $source . "','" . $finalPdf . "','y',0,0);";
echo $query;
$result = $conn->query($query);
echo $result->num_rows;
$conn->close();
When this runs I get a return of INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq VALUES ('m','scan/WF_153_140812113520.pdf','y',0,0);, but I get no return of number rows.
I really just need the ID right this minute of the inserted row, but if we can get all of these fields that would be awesome.
I pretty much copied the usage of the OUTPUT clause from a few different places, but I don't see what I'm doing wrong to get no return...
I'm trying to do some research while writing this as I have not had good response rates because people think I'm lacking it so I also found: How do I use an INSERT statement's OUTPUT clause to get the identity value?... I changed my query only to:
$query = "DECLARE #OutputTbl TABLE (id INT, src VARCHAR, loc VARCHAR, iq INT, wq INT, pq INT);
INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.id, Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq INTO #OutputTbl(id, src, loc, iq, wq, pq) VALUES ('" . $source . "','" . $finalPdf . "','y',0,0);";
I sadly still get nothing.. Hopefully this will give enough info as to what I should do next.
#cmorrissey provided a great solution...
$last_insert_id = $conn->insert_id;
This returns the last inserted id (I think primary key that is auto incremented is the most correct explanation.) This is better to use than OUTPUT. I'm not sure why OUTPUT is incorrect to use as I have seen it so many places and this only once from the user.
I am trying to insert data into Mysql table, but it is giving me an error as-
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 'Scoretab VALUES ('UX 345','22','0.8562675')' at line 1
This is the php-mysql snippet that im using :
if($value >= 0.70){
$mu_id = $ros['c_id'];
$moc_id = $ram['t_id'];
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
$op1 = mysql_query($query) or die(mysql_error());
}
This is my table structure:
CREATE TABLE IF NOT EXISTS `Scoretab` (
`mu_id` varchar(10) NOT NULL,
`moc_id` int(5) NOT NULL,
`score` decimal(5,4) NOT NULL,
UNIQUE KEY `mu_id` (`mu_id`)
)
There could potentially be a few problems with this query
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
Does the number of columns match the fields your trying to insert? Have you tried using using specific column identifier Scoretab (col,col,col) values (val, val, val)
Does any of your values contain an unescaped apostrophe? You might want to consider using mysql_real_escape_string for $mu_id and intval for $moc_id maybe!
$value is a float you don't need to ad apostrophes while inserting
Are you sure you are connected to the same database you have this table in?
this could be a possible working solution (edit)
if ($value >= 0.70)
{
$mu_id = mysql_real_escape_string($ros['c_id']);
$moc_id = intval($ram['t_id']);
$query = "INSERT INTO `Scoretab` VALUES ('$mu_id', $moc_id, $value)";
$op1 = mysql_query($query) or die(mysql_error());
}
try this
$query="INSERT INTO Scoretab (mu_id,moc_id,score) VALUES ('$mu_id','$moc_id','$value')";
The error seems to be before the table name Scoretab. Did you check your syntax carefully?
Sometimes we don't see what's right in front of our eyes! :D
Just replicated the example and everything worked for me.
So I have this,
<?php
require "database.php";
$to=$_GET['toF'];
$content=$_POST['message_contentl'];
$from=$_GET['fromF'];
$ck_reciever = "SELECT Username FROM accounts WHERE username = '".$to."'";
if( mysql_num_rows( mysql_query( $ck_reciever ) ) == 0 ){
die("The user you are trying to contact don't exist. Please go back and try again.<br>
<form name=\"back\" action=\"Send_FR.php\" method=\"post\">
<input type=\"submit\" value=\"Try Again\">
</form>
");
}else{
$a1 = $_POST['message_contentl'];
$a2 = $_GET['fromF'];
$a3 = $_GET['toF'];
mysql_query("INSERT INTO Friends (fr_message, From, To) VALUES ('$a1', '$a2', '$a3')"); OR die("Could not send the message: <br>".mysql_error());
echo "The Friend Request Was Successfully Sent!";
?>
But it doesn't work.
All it does is give me this 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 'From, To) VALUES ('', 'Extro', 'Syncro')' at line 1
Help, please?
from and to are reserved words in SQL, in MySQL you can use reserved words as column or table names by wrapping them in backticks, but I'd strongly advise against the use of reserved word as column names, it's horribly confusing. Small example ex absurdo:
select `select`, `from` from `where` where `like` like 'like';
Yeah, the engine eats it, but you'll admit it could be more readable :-)
FROM is a reserved SQL keyword - if you have a column or a table with that name, you will have to back-quote (`) it.