issue Updating table - php

I have an app that I am trying to use to update a mysql table which has the following layout:
I am trying to get it so that the app sends in the URL the employee name and the in/out column value, and then my PHP script finds the person with the matching name and changes the in/out column value. Here is an example of an entry:
For some reason, when the in/out column should be changing to a 1, it remains at 0.
My Script is as follows:
<?php
// Input the credentials, clocktablet would be the database name
$con=mysqli_connect("localhost","tablet1","*****","clocktablet");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$employeename = mysqli_real_escape_string($con, $_GET['employeename']);
$Clock = mysqli_real_escape_string($con, $_GET['Clock']);
//alters Track Table to display in/out status
$sql = "UPDATE track SET In/Out=$Clock WHERE EmployeeName=$employeename";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Can anyone see anything wrong with the php script?
The table name is Track and the DB name is clocktablet, and I can confirm that the username and password inputted into the script is correct.

Missing quotes in column values and backtick in column name for exm In/Out .
Better use prepare statement!!
//alters Track Table to display in/out status
$smt = $con->prepare("UPDATE `track` SET `In/Out`=? WHERE `EmployeeName`=?");
$smt->bind_param('is',$_GET['Clock'],$_GET['employeename']);
$smt->execute();
To check number of affected rows by update query use
printf("Affected rows (UPDATE): %d\n", $con->affected_rows);

Change
$sql = "UPDATE track SET In/Out=$Clock WHERE EmployeeName=$employeename";
To
$sql = "UPDATE track SET `In/Out`=$Clock WHERE EmployeeName='$employeename'";
^ enclose column name with backtick
May be column name with backslash are allowed while creating a table. But, while inserting value for that column. It need to be enclosed with backtick, otherwise, it will through an error stating
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 'in/out
Backtick

Use single quotes around $employeename and backtick in column name for In/Out
$sql = "UPDATE track SET `In/Out`= $Clock WHERE EmployeeName= '$employeename'";

Related

Error in phpmysql database connectivity

<?php
require 'database.inc.php';
$query="SELECT 'food','calorie' FROM 'users' ORDER BY 'id' " ;
if($query_run=mysql_query($query))
{echo '<br> working';}
else {echo '<br>nothing error';
echo mysql_error();} ?>
ERROR:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''users'
Replace all your ' with `(this is the sign below ~ in keyboard) as:
$query="SELECT `food`,`calorie` FROM `users` ORDER BY `id`";
Delete all single quotes ' in your query :
$query="SELECT food,calorie FROM users ORDER BY id";
No need to use the quotes for table name or field name. instead use back quotes if needed (`).
For normal field names it is not mandatory. if table contain any field name, that is a mysql key name, it is mandatory.
for eg:- if column name "group" exists. with out back quotes it will throw error.
$query="SELECT `food`,`calorie` FROM `users` ORDER BY `id` " ;

Getting syntax error when trying to update numerical value (MySQL)

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?

php mySQL error of syntax

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

PHP/MySQL Concat to a single column and Update other columns in table

Am trying to only concat new updates to column updates and UPDATE the values in the rest of the columns but I've hit bit of a snag that I can't seem to workout.
My SQL looks like this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";
the updates column is like a comments column, where new updates are meant to be appended to the existing text.
The error I'm getting on the web server:
Update tickets SET product='T-Box', p='00000817766', i='-', summary='Testing update field
\r\nAdding an update\r\ntesting if null works for update', workaround='n/a', concat(updates,' ','test2#18:53:17:second update/n'), status='Open', raised_by='No', updated_by_user='test2' WHERE id='223'
Running the query directly in MySQL:
#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 '(updates,'test2#18:53:17:second update/n'), status='Open', raised_by='No', updat' at line 1
Help is much appreciated!
You need to specify where the value of this statement concat(updates,'$additional_update') to be set.
Update tickets
SET product = '$product',
p = '$p',
i = '$i',
summary = '$summary',
workaround = '$workaround',
updates = CONCAT(updates,'$additional_update'), // <== see this
status = '$status',
raised_by = '$raised_by',
updated_by_user = '$updated_by'
WHERE id = '$id'
try this:
$query="Update tickets SET product='$product',
p='$p',
i='$i',
summary='$summary',
workaround='$workaround',
updates=concat(updates,'$additional_update'),
status='$status',
raised_by='$raised_by',
updated_by_user='$updated_by' WHERE id='$id'";

Update int in MySQL Field

How can I increment an int in a cell of a MySQL database? I know that auto-increment is no use because I never want to add a new row, just update an existing one. I'm currently using this (POST var used for clarify, is verified in the real code):
$columnToUpdate = 'type'.$_POST['voteid'];
$query = "UPDATE myTable $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
if(!mysql_query($query)) {
echo json_encode(array('success' => false, 'message' => 'Update failed: '.mysql_error()));
exit;
}
In the database I have 6 fields, id, type1, type2, type3, type4, type5, and a single row with id set to 1. The intention is to recieve a number (1-5), and build a reference to the correct column before updating the field. That results in Update failed: 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 '=type4+1 WHERE id=1' at line 1, so I guess it's not getting the field value out properly before it increments.
Once this is working I'm also going to need to decrement a field in the same way, unless its value is 0. So for bonus points, can I do all this in one query or would it be better to split it up?
I think you've missed the keyword 'SET' from your query - try
$query = "UPDATE myTable SET $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
Edit:
To do the "decrement unless it's zero" you could use something like:
UPDATE myTable SET $columnToUpdate =
CASE $columnToUpdate
WHEN 0 THEN 0
ELSE $columnToUpdate - 1
END CASE
WHERE id=1;`
For bonus points, to decrement:
$query = "UPDATE myTable SET '$columnToUpdate' = '$columnToUpdate'-1 WHERE id=1 AND '$columnToUpdate' > 0";
Besides the injection issues, it seems as if your workflow may need some work. Are you sure you want to choose the column that will be updated based on POST variable? It seems like you would specify the column and use the variable to find the record that needs to be updated:
IE:
"UPDATE myTable SET votes=votes+1 WHERE id=$post_variable;"
Again you should send the variable as a parameterized query to protect yourself from SQL injection.

Categories