I am an amateur programmer creating a PHP based online portal which will update values in a MySQL database in relation to a MMO-type game, in which we are using the portal to track a total number of land tiles protected by each user.
I am working on the script which will update the table count for a given type of protected land, upon submission of an HTML form through a $_POST array.
The MySQL table (players) in question has four similar fields (along with other fields):
wild_count
city_count
nether_count
end_count
On the HTML form, the user can select a land type when submitting, and the script attempts to perform a string concatenate to complete the field, then supplies this for the placeholder in the prepared SQL query, as such:
//Set land type string
$landtype = $_POST['landtype'] . '_count';
//Process ADD request
if (!isset($_POST['negative']))
{
$action = 'ADDED'; //This is for a transaction report further down in the code
try
{
$sql = 'UPDATE players SET
`:landtype` = `:landtype` + :tiles WHERE id = :id';
$query = $link->prepare($sql);
$query->bindValue(':landtype', $landtype);
$query->bindValue(':tiles', $_POST['tiles']);
$query->bindValue(':id', $_POST['player']);
$query->execute();
}
catch (PDOException $e)
{
$error = 'Error updating land count: ' . $e->getMessage();
include './includes/error.inc.php';
exit();
}
...more code follows...
When trying to POST my form using the following code, I get the following error:
Error updating land count: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''city_count'' in 'field list'
(I had selected city in my form example).
I've tried the same code, except without the backticks around the placeholder :landtype (i.e. $sql = 'UPDATE players SET :landtype = :landtype + :tiles WHERE id = :id';) and I get a different error:
Error updating land count: 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 ''city_count' = 'city_count' + '300' WHERE id = '1'' at line 2
I'm not certain how to proceed. Does the attempt at setting the field value by creating a concatenated string break it here?
Don't try to bind column name like it's a value:
$sql = 'UPDATE players SET `'.$landtype.'` = `'.$landtype.'` + :tiles WHERE id = :id';
Can PHP PDO Statements accept the table or column name as parameter?
Related
I am having an issue displaying a table from my database. Every time I run the page I get this error message:
There was an error running the query [Unknown column 'song.songTitle' in 'field list']
Here is a $sql code block I am trying to pull the data from my table to my PHP form with:
Upper Switch Statement
code case "songAlbum": {
$tableFormat=SONG_ALBUM;
$sql = "SELECT song.songTitle, song.url, album.albumTitle, album.albumPrice
FROM song
JOIN album
WHERE song.album_id = album.album_id
ORDER BY album.albumTitle";
break;
}
Thanks for the help.
Name of the column is song_title, not songTitle
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)
Im using mysql, when I want to update a column with this query
UPDATE books
SET ISBN = $ISBN
, Title = '$BookTitle'
, PublicationDate = '$PublicationDate'
, Publisher = '$Publisher'
, Edition = $Edition
, Volume = $Volume
, books.Author_AuthorId = $AuthorId
WHERE ISBN = $GETISBN;
with php it works well while all the input are filled in HTML FORM but if one input is empty already or I clear the previous data in HTML Form and Submit the Form it issues this 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 'Volume=1, books.Author_AuthorId=3 WHERE ISBN=5456165156' at line 2
What Should I do?
Here is the query which I have echoed
UPDATE `books` SET `ISBN`=5456165156,`Title`='500 Notice About Java',`PublicationDate`='1390-05-25', `Publisher`='Qods Publication',`Edition`=,`Volume`=1, `books`.`Author_AuthorId`=3 WHERE `ISBN`=5456165156
As long as The $Edition is empty Then The Query Changes like this
`Edition`=
Thats why Mysql can not Understand what value should be set to Edition
I'm not a newbie to PHP but I have encountered a [seemingly] simple problem which I cannot figure out how to resolve.
MySQL throws error that the syntax is wrong.
My Statement is this:
if($value){
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
$db->sql_query( $query ) or die( mysql_error() );
}
And then $words_amount is an integer, $sn_id is also an integer. They are double checked.
The statement when printed before execution is as follows:
UPDATE SET uploads words = '250' WHERE id= 8081
// edited, with the name of table added since the problem primarily was
// with the encapsulation and the name of table just was dropped in this question
// and not in the app
however words value ('250') is tested with integer data-type as well, but no change occurs and the error lingers on.
And the error thrown is:
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 'SET words = '250' WHERE id= 8081' at line 1
If I understand your question (and preuploads is a table), then
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
should be
$query = "UPDATE ".$preuploads." SET words = '".$words_amount."' WHERE id=".$sn_id;
Or, even better prepare and use bind_param,
$stmt = $mysqli->prepare("UPDATE ? SET words=? WHERE id=?");
$stmt->bind_param($preuploads, $words_amount, $snd_id);
$stmt->execute();
check your string ($words_amount) has any single quotes ' if it is then remove it by using this option on php $words_amount=string_replace("'","/'",$your_string_variable);
I have found two errors:
First, not encapsulation of the data should occur, thus:
$words_count should be left as is, not to be encapsulated with '
And the table and fields name should be encapsulated with backtick
I think your having problem with name of table. The syntax for update query is
UPDATE table_name SET words = '250' WHERE id= 8081
I want to log what a user enters into a PHP form, and make sure they are not entering data that already exists in a database table.
I have the code already that enters the data into the table from user input, but I'm not sure how to check for duplicates. For example I want to check that there is no product under the same name being added again.
$sql = "
INSERT INTO user_date
SELECT
product_name = '$_POST[product_name]'
,code = '$_POST[code]'
,comments = '$_POST[comments]'
WHERE
NOT EXISTS(SELECT * FROM user_data WHERE product_name = '$_POST[product_name]') ";
But I get an 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 '= 'fdgfdg' code = 'fdgdfg' WHERE NOT EXISTS(SELECT *' at line 4
I'm aware of the security issues. Its not a live system but just to learn from it.
If you don't want to have duplicate insert then use IGNORE at end of insert statement
$sql = "
INSERT INTO user_date
values
('$_POST[product_name]'
,'$_POST[code]'
,'$_POST[comments]')
ON DUPLICATE KEY IGNORE";
So this way might help you
$result = mysql_query("SELECT * FROM user_data WHERE product_name = '$_POST[product_name]'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}