SQL, PHP update query - php

I was wondering if there is any way to check if the update query has executed successfully or else I will execute insert query.
$record = mysql_query("update table set a='$b', b='$c' where id = '$id' ");
echo $record; // returns always 1;
Thank You.

Use the mysql_affected_rows function to find the number of records affected. Please see following code.
$record = mysql_query("update table set a='$b', b='$c' where id = '$id' ");
$total_rows = mysql_affected_rows($conn);
echo $total_rows;
where $conn is the connection object

It will be like
$records = mysql_query("UPDATE `table` SET a='$b', b='$c' WHERE id = '$id' ");
$affected_rows = mysql_affected_rows($records);
if($affected_rows >= 1) {
echo "Updated ".$affected_rows." rows";
}
Need to remove $ before mysql_query.And consider that table is your table name and also makesure that your connection to the DB is active.
And Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

Try this ... It returns the number of modified rows in the last query run.
$Rows = mysql_affected_rows($record).
example $Rows = 1, 2, 3 etc......
mysql_query(): how to check whether any rows are updated in case of UPDATE SQL

mysql_affected_rows() is what you need.
Docs: http://php.net/manual/en/function.mysql-affected-rows.php
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
if (mysql_affected_rows() > 0) {
echo 'You updated '.mysql_affected_rows(). 'rows.';
} else {
echo 'Nothing updated';
}

Related

If Else Statement Not Working - PHP

I'm making a simple auction website and I'm trying to keep the user from bidding on an item if they are already the highest bidder. At the moment, however, my code still allows the highest bidder to continue bidding and I get an error saying that mysql_fetch_array() expects paramater 1 to be resource.
Any idea where I'm going wrong? Here is my code:
<html>
<head></head>
<body>
<?php
session_start();
require_once("dbconnect.inc");
$accountid=$_SESSION['accountid'];
$itemid=$_POST['itemid'];
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditem = '$itemid' ORDER BY bidhistoryid DESC");
while($row = mysql_fetch_array($result)){ //
$checkaccountid = $row['accountid'];
if($checkaccountid == $accountid){ /* THEN COMPARE IT WITH THE CURRENT USER */
echo "You are the highest bidder!";
}
else { // they can still bid
$sql="INSERT INTO bidhistory (accountid, biditemid)
VALUES ($accountid, $itemid)";
mysql_query("
UPDATE bidhistory
SET bidprice = bidprice + 1
WHERE biditemid = " .
#mysql_escape_string($itemid));
$result=mysql_query($sql) or die("Error in adding bid for item: ".mysql_error());
}
}
echo "Bid accepted!";
?>
<p>Back to auction</p>
</body>
</html>
Your query is incorrect for your first select.
biditem =
should be
biditemid
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditemid = '$itemid' ORDER BY bidhistoryid DESC");
You also are open to SQL injections with this code. User input and SQL queries should be separated. To do this use prepared statements. The mysql_ functions don't have support for this and are outdated. You should switch DB drivers either the PDO or mysqli should suffice.
One approach you could take is casting the itemid to an int (presuming it is an int).
$itemid= (int)$_POST['itemid'];
Then
$result = mysql_query("SELECT accountid FROM bidhistory
WHERE biditemid = $itemid ORDER BY bidhistoryid DESC");
Additional information on injection prevention.
How can I prevent SQL injection in PHP?
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
An example using PDO and the query parameterized (http://php.net/manual/en/pdo.prepared-statements.php).
$parameterize = $dbh->prepare('SELECT accountid FROM bidhistory
WHERE biditemid = ? ORDER BY bidhistoryid DESC');
$parameterize->execute(array($itemid));
The ? here is a placeholder for the user provided value.
You need to check to confirm that $result contains a successful query result. If it failed it will be 'false' and your request to fetch the data will fail as reported.
From PHP documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Check your SQL query. There may be an error, or no matching data were found on the database.
Also, mysql_query is deprecated as of PHP 5.5.0, and will be removed in the future. You should start thinking about using mysqli_query or PDO.
The problem is not in if and else statement but in the query. If you see this error ("mysql_fetch_array() expects parameter 1") directly think about your query.
Before my answer I advise you to use mysqli not mysql, your query should be like this:
$query="SELECT 'accountid' FROM `bidhistory`
WHERE 'biditem' = '".$itemid."' ORDER BY 'bidhistoryid' DESC"

Unable to INSERT any records in MYSQL from PHP

So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>

How to check if a row exists compared to another value

I am not sure how to go about this in PHP & MySQL;
But basically, I just want to check to see if a row exists in a table, and if it does, return a error, example:
$exists = MYSQL CODE TO CHECK HOW MANY ROWS INCLUDE BADGE_ID
if($exists >= 1)
{
$errors[] = "Exists.";
}
Something like that, because I'm coding a small shop script and I want it to check to make sure that they don't already have the badge_id. Structure of the db is user_id and badge_id (user_id = 1, badge_id = 1; for an example)
//Mysql
$res = mysql_query("YOUR QUERY");
if(mysql_num_rows($res) > 0) {
$errors[] = "Exists.";
}
//PDO
$query = $db->prepare("YOUR QUERY");
$ret = $query->execute();
if($ret && $query->rowCount() > 0) {
$errors[] = "Exists.";
}
for this query as
$query=mysql_query("SELECT * from table WHERE userid = 1 AND badgeid = 1");
and in php
if(mysql_num_rows($query)>0){
// whatever you want if match found
}else{
echo "No match Found".
}
$sql = "SELECT COUNT(*) FROM `table_name` WHERE `user_id` = '1' AND `badge_id` = '1' "
$exists = mysql_query($sql) ;
if(mysql_num_rows($exists) >= 1) {
$errors[] = "Exists.";
}else {
// doesn't exists.
}
Try using PDO instead of the old mysql_query() functions for they are deprecated since PHP 5.5.
For a simple query:
$slcBadge = $con->query('SELECT badge_id FROM badges');
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Or if you want to fetch all rows from a single user:
$sqlBadge = 'SELECT id_badge FROM badges WHERE id_user = :idUser';
$slcBadge = $con->prepare($sqlBadge);
$slcBadge->bindParam(':idUser', $idUser, PDO::PARAM_INT);
$slcBadge->execute();
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Notice that in the second piece of code I used prepare() and execute() rather than query(). This is to protect you query from SQL injection. By using prepare() you fix the construct of your query so if a user enters a query string as a value, it will not be executed. You only need to prepare a query if a user can enter a value which will be used in your query, otherwise query() will do just fine. Check out the injection link for more detailed info.
Your version of PHP is important:
mysql_* functions are deprecated as of 5.4, and
Removed as of 5.5
It is advised to either implement PDO or Mysqli
mysql:
This extension is now deprecated, and deprecation warnings will be generated when connections are established to databases via mysql_connect(), mysql_pconnect(), or through implicit connection: use MySQLi or PDO_MySQL instead
Dropped support for LOAD DATA LOCAL INFILE handlers when using libmysql. Known for stability problems
Added support for SHA256 authentication available with MySQL 5.6.6+
For reference please see the changelog
Structuring your Query
First of all I'm assuming you are indexing your fields correctly refer to this article I posted on Stack Exchange.
Second of all you need to consider efficiency depending on the volume of this table: doing a SELECT * is bad practice when you only need to count the records - mysql will cache row counts and make your SELECT Count(*) much faster. with indexes this is furthermore efficient.
I would simply consider something along the line of this:
$dsn = 'mysql:host=127.0.0.1;dbname=DATABASE';
$db = new PDO($dsn, 'username', 'password', array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
));
NOTE:
where host=127.0.0.1 if your user has been granted access via localhost then you need this to state localhost - or grant the user privileges to 127.0.0.1
NOTE:
with SET NAMES there is also a bug with the PDO driver from 5.3 (I believe) whereby an attacker can inject nullbytes and backspace bytes to remove slashing to then inject the query.
Quick example:
// WARNING: you still need to correctly sanitize your user input!
$query = $db->prepare('SELECT COUNT(*) FROM table WHERE user_id = ? AND badge_id = ?');
$query->execute(array((int) $userId, (int) $badgeId));
$total = $query->fetchAll();
$result = mysql_query("SELECT COUNT(*) FROM table WHERE userid = 1 AND badgeid = 1 LIMIT 1") or die(mysql_error());
if (mysql_result($result, 0) > 0)
{
echo 'exist';
}
else
{
echo 'no';
}

MySql statement returning incorrect results

I am trying to receive an Id from my user table.
I have:
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$user_id = intval(mysql_query($retrieve_id));
The statement should return 1 since that is the value in the table. However, it returns 6 which is the length of the column name (userid). This happens when I'm querying other tables too.
How can I retrieve the value from the table ONLY?
You need to fetch the actual result from the query, either using mysql_result or mysql_fetch_*.
$result = mysql_query("SELECT userid FROM tb_users WHERE username = '$username'");
if (!$result) {
die('Could not query:' . mysql_error());
}
$user_id = mysql_result($result, 0); // outputs first row
Note that all mysql_ functions are deprecated and you should use mysqli_ or PDO. Your query is also open to SQL injection.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource not the value.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_fetch_assoc(mysql_query($retrieve_id));
$user = $result['userid'];
A) mysql_* is deprecated
B) make sure you're parameterizing your inputs
C) try this:
$result = mysql_query($retrieve_id);
$user_id=$result["userid"];
function mysql_query returns resource type for a select query. For results you have to use mysql_fetch_array or mysql_fetch_assoc functions.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_query($retrieve_id));
$row = mysql_fetch_assoc($result)) {
echo $row['userid'];
Check the php docs on mysql_query(). It actually returns a resource, not simply the value you are querying for.
But you shouldn't even be using mysql_query() as it's deprecated in PHP 5.5, and you don't want to have to redo your code when you upgrade, do you?
Instead, use mysqli_query(), which will return a mysqli_result object. Then from that object, you can retrieve the values you're looking for with fetch_field()

IF and ELSE statement not working

I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}

Categories