How to check if a row exists compared to another value - php

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';
}

Related

PHP check if MySQL table contains variable

So I am new to php and I am trying to check if a mysql table contains a variable which is set when a user does a search. If the table contains the variable (it's a string) then I want to be able to do different things depending on its existence.
I should also note that I am a novice with php development!
This is what I have so far;
$db = new mysqli('IP', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = $searchVar");
if(empty($result)){
//No result Found
}else{
//Found result
}
You need to place single quotes around $searchVar in the query.
$result = $db->query("SELECT * FROM tablename WHERE ColumnName = '$searchVar'");
Then, you must fetch the results of the query.
$result = $result->fetch_row();
Okay so your current query failed because your SQL string wasn't in quotes. It also could have failed once inputted into quotes if your PHP string had a single quote in it. This is how SQL injections occur, user input should never be passed directly into a SQL query. To separate these tasks there are prepared/parameterized queries.
Here's code I think should work for you but this is untested, based off manuals.
$db = new mysqli('IP', 'username', 'password', 'database');
$stmt = $db->prepare('SELECT * FROM tablename WHERE ColumnName = ?');
$stmt->bind_param('s', $searchVar);
$stmt->execute();
if($stmt->num_rows > 0) {
echo 'there are results';
} else {
echo 'there are no results';
}
Link to thread on preventing injections: How can I prevent SQL injection in PHP?

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"

How can I write a php code for data can not find in table of MySQL database?

I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php

SQL, PHP update query

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';
}

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