how can i update my table column with php mysql using increments - php

i am creating a page that has a verification function when an order is succesful
i am trying to increase the value of a column incrementally using a variable
but i keep get an error
Error updating record: 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 '+ '57' WHERE Username = 'kokoman'' at line 2
This what i am working with for the increment
$sql = "UPDATE users
SET package = '$packagex', diamonds + $diamondx, rate = '$ratx', amount + $amountx
WHERE Username = '$usernamex'";
That keeps generating the above error
i am using that because i know if i need to increase the value of a column
i would just use "set column +1"
but now i am trying to use a variable because it has to be dynamic but i get the error
please help tanks

The SET clause needs to contain assignments. diamonds + $diamondx should be diamonds = diamonds + $diamondx, and similarly for the other columns.
You should also stop substituting variables into queries and learn to use prepared statements with parameters.

From my understanding you want add value to previously held values of columns amount and diamondsfor that, Try this:
$amountx = 1;
$diamondx = 1;
$sql = "UPDATE users
SET package = '$packagex',
diamonds = diamonds + $diamondx,
rate = '$ratx',
amount = amount + $amountx
WHERE Username = '$usernamex'";

Related

Unable to perform mysql table insertion

I am unable to find any error shown but for some reason there is still an issue entering data into my table using SQL. I am new to coding and am not really sure what the issue is . I am sure that everything that needs to be passed and given is done but the mysql query is where it goes wrong and i am not able to understand why . could someone please help me out ?
<?php
session_start();
$conb = mysqli_connect("127.0.0.1","root","","demo");
$sellmail = $_SESSION['sellermaill'];
$buyermail = $_POST['email'];
$bid = $_POST["bid"];
$title = $_SESSION["Titleofp"];
echo"$sellmail";
echo"$buyermail";
echo"$bid";
echo"$title";
$mysqlbuy = "INSERT INTO buyer (Seller Mail,Buyer Mail,Bid,Product Title) VALUES ('$sellmail','$buyermail','$bid','$title')";
$mysqlsellq = mysqli_query($conb,$mysqlbuy);
if(!$mysqlsellq)
{echo "Your Bid has not been saved ";}
else echo "Your Bid has been Saved ";
?>
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 'Mail,Seller Mail,Product Title,Bid) VALUES
('rao.7#gmail.com','rsk101295#gmail.c' at line 1
(I) Change your column name in Database table:
1)Seller Mail to Seller_Mail
2)Buyer Mail to Buyer_Mail
3)Product Title to Product_Title
Then insert
$mysqlbuy = "INSERT INTO buyer (Seller_Mail,Buyer_Mail,Bid,Product_Title) VALUES ('$sellmail','$buyermail','$bid','$title')";
Embedded spaces or special characters are NOT ALLOWED in column name.
For more info, click Characters that are not allowed in table name & column name
OR
(II)
If, you don't want to put underscore in column name or don't want to modify your column name. Use like this. (Use Backtick to enclose column name.). But, make sure you follow naming conventions of column name.
$mysqlbuy = "INSERT INTO buyer (`Seller Mail`,`Buyer Mail`,`Bid`,`Product Title`) VALUES ('$sellmail','$buyermail','$bid','$title')";
For more info, Please click How to select a column name with space between in mysql
Find Backtick in Keyboard:

Unable to subtract a table value via variable

I can not get an SQL update statement to subtract a variable from a table value. Here is my code:
$_SESSION_Job101=mysql_fetch_array(mysql_query("SELECT * FROM job_101 WHERE job_101.username='$_SESSION_User'"));
mysql_query("UPDATE characters SET currenergy=currenergy-$_SESSION_Job101['ecost'] WHERE username='$_SESSION_User'");
$_SESSION_Job101 is a perfectly valid result, as I pull from it on another page; I even pull the 'ecost' on said page. I also update currenergy this way in another script, except I use the number 1 instead of the variable. So I've narrowed it down to that variable.
It wouldn't matter that $_SESSION_Job101 is the result from a second table (job_101), and that query is updating to the table characters, would it?
We don't have enough information, but since you don't perform ANY error handling or validation that SQL resultset is returned, it could be an error caused by issues such as:
no rows returned in first query
some other parsing issue not directly evident
I would propose that you use temporary strings and echo the actual SQL queries.
Continue by actually testing them with MYSQL (through workbench, queryviewer, or console) in order to see where and what the error is.
Also, it's not recommended to skip error checking and try to combine so many lines/steps into 2 lines.
Imagine the first query does not return any results for example...
Debugging:
$query1 = "SELECT * FROM job_101 WHERE job_101.username='$_SESSION_User'";
echo $query1."<br/>";
$_SESSION_Job101=mysql_fetch_array(mysql_query($query1 ));
$query2 = "UPDATE characters SET currenergy=currenergy-$_SESSION_Job101['ecost'] WHERE username='$_SESSION_User'";
echo $query2."<br/>";
mysql_query($query2);
Update
Based on your comment I suggest you try the following two options:
1) Add a space between the - and $_SESSION_Job101['ecost'].
2) If that doesn't work, change your string to:
mysql_query("UPDATE characters SET currenergy=currenergy-".$_SESSION_Job101['ecost']." WHERE username='".$_SESSION_User."'";`

plus 1 to column each time page viewed?

can someone please help i am trying to make a kind of view count, to reflect the number of times a post has been viewed.
I am trying to create a function in mysql which will add +1 to a column called read in my table. so if the count starts from 0 in the column and each time someone opens that post it adds a 1 and another 1 and another 1 for however many times the page has been accessed.
i am trying to do this but am failing miserably can someone please show me how to achieve this type of thing please.
function read_forum_set() {
global $connection;
global $forum_id;
$query = "SELECT *
FROM ptb_forum, ptb_profiles
UPDATE ptb_forum.read_forum +1
WHERE ptb_profiles.user_id = ptb_forum.from_user_id
AND ptb_forum.id = '$forum_id' ";
$read_forum_set = mysql_query($query, $connection);
confirm_query($read_forum_set);
return $read_forum_set;
}
You need an update with join:
update ptb_forum
join ptb_profiles on ptb_profiles.user_id = ptb_forum.from_user_id
set ptb_forum.read_forum = ptb_forum.read_forum + 1
where ptb_forum.id = $forum_id
Whatever you do, make sure you use update ... set column = column + 1 and not two separate queries (one to read the old count and one to update it) because only with a single update expression you will be sure that each hit is counted exactly once.
First of all it's probably better to separate the queries out for sanity sake.
As for an increment query, very simple
UPDATE table
SET column = column + 1
WHERE foo = bar

joomla-php mysql not updating a record with data from previous query

I'm counting the right answers field of a table and saving that calculated value on another table. For this I'm using two queryes, first one is the count query, i retrieve the value using loadResult(). After that i'm updating another table with this value and the date/time. The problem is that in some cases the calculated value is not being saved, only the date/time.
queries look something like this:
$sql = 'SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId;
$db->setQuery($sql);
$rightAnsCount = $db->loadResult();
$sql = 'UPDATE #__testsTable
SET finish = "'.date('Y-m-d H:i:s').'", rightAns='.$rightAnsCount.'
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
answer = 1 means that the question was answered ok.
I think that when the 2nd query is executed the first one has not finished yet, but everywhere i read says that it waits that the first query is finished to go to the 2nd, and i don't know how to make the 2nd query wait for the 1st one to end.
Any help will be appreciated. Thanks!
a PHP MySQL query is synchronous ie. it completes before returning - Joomla!'s database class doesn't implement any sort of asynchronous or call-back functionality.
While you are missing a ';' that wouldn't account for it working some of the time.
How is the rightAns column defined - eg. what happens when your $rightAnsCount is 0
Turn on Joomla!'s debug mode and check the SQL that's generated in out the profile section, it looks something like this
eg.
Profile Information
Application afterLoad: 0.002 seconds, 1.20 MB
Application afterInitialise: 0.078 seconds, 6.59 MB
Application afterRoute: 0.079 seconds, 6.70 MB
Application afterDispatch: 0.213 seconds, 7.87 MB
Application afterRender: 0.220 seconds, 8.07 MB
Memory Usage
8511696
8 queries logged.
SELECT *
FROM jos_session
WHERE session_id = '5cs53hoh2hqi9ccq69brditmm7'
DELETE
FROM jos_session
WHERE ( TIME < '1332089642' )
etc...
you may need to add a semicolon to the end of your sql queries
...testId = '.$examID.';';
ah, something cppl mentioned is the key I think. You may need to account for null values from your first query.
Changing this line:
$rightAnsCount = $db->loadResult();
To this might make the difference:
$rightAnsCount = ($db->loadResult()) ? $db->loadResult() : 0;
Basically setting to 0 if there is no result.
I am pretty sure you can do this in one query instead:
$sql = 'UPDATE #__testsTable
SET finish = NOW()
, rightAns = (
SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId.'
)
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
You can also update all values in all rows in your table this way by slightly modifying your query, so you can do all rows in one go. Let me know if this is what you are trying to achieve and I will rewrite the example.

SQL Syntax Error when using primary key with WHERE

I am trying to use UPDATE with my MySQL-Database. I use the following SQL code:
$sql = "UPDATE ToDo
SET Checked = -1
WHERE Index = 1";
When I use this code i get the following 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 'Index = 1' at line 3"
But when I use
$sql = "UPDATE ToDo
SET Checked = -1
WHERE Text = 'asdf'";
Everything works.
My database has one table named "ToDo" with 3 collumns: Index(int, primary key, auto_increment), Checked(bool) and Text(text).
Can't you "WHERE" a primary key or did i forget something else?
Hope you can help me.
Try adding the backticks:
UPDATE ToDo
SET `Checked` = -1
WHERE `Index` = 1";
Index is a reserved word :
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
index is a reserved word for MySQL. You need to esacpe the name by adding backticks like this:
$sql = "UPDATE ToDo
SET Checked = -1
WHERE `Index` = 'asdf'";
In order to make sure MySQL understands that you are talking about a column name and not the reserved word, you can always address the column name tablename.columnname.
In SELECT queries also using shortcuts is possible:
UPDATE ToDo SET ToDo.Checked = -1 WHERE ToDo.Index = 1
SELECT u.Index FROM users u
Also I would recommend not to use camel cases in tables and columns. This proved to be a source for errors and has no real benefit most of the time.
Boolean is 0 or 1, not -1. Try using 0 or 1 for Checked and let us know what happens.

Categories