PHP check if MySQL table contains variable - php

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?

Related

Retrieving data from database gives error

Can anyone help me with this? My code won't run and I can't figure out why not.
<?php
include('connect-db.php');
if (isset($_GET['naam']))
{
// query db
$naam = $_GET['naam'];
$result = mysql_query("SELECT * FROM planten WHERE naam=$naam")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
// get data from db
$cat = $row['cat'];
$mintemp = $row['mintemp'];
$uitleg = $row['uitleg'];
$img = $row['img'];
}
}
?>
The connection is working and active, and the database name & row names are correct.
Try this
$result = mysql_query("SELECT * FROM planten WHERE naam='".$naam."'") or die(mysql_error());
I think the problem is in your query statement. Since $naam is string you need to use quotes to enclose the string in query. Please chnage your query statement as below and try:
$result = mysql_query("SELECT * FROM `planten` WHERE `naam` ='$naam'");
I guess your $naam is supposed to be a string. You should escape and quote it. Otherwise it'll be interpreted by SQL as a bogus column name.
if (isset($_GET['naam']))
{
// query db
$naam = mysql_real_escape_string($_GET['naam']);
$result = mysql_query("SELECT * FROM planten WHERE naam='$naam'")
or die(mysql_error());
...
This would be safer and easier if you use PDO with SQL query parameters. No need to escape anything or worry about quotes, because it's all taken care of for you by using a parameter.
if (isset($_GET['naam']))
{
// query db
$sql = "SELECT * FROM planten WHERE naam=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_GET['naam']]);
...
FYI the old "mysql_connect()" API was deprecated in PHP 5.5 (June 2013), and has been removed in PHP 7.0 (Dec 2015). See http://php.net/manual/en/mysqlinfo.api.choosing.php.
I recommend using PDO.

How to prevent weird user inputs from breaking things in queries?

Is there a good standard solution to deal with characters like ' and " from being used in user inputs on a web platform?
I'm using php for a webpage and if I have, for example, a search bar which have the following query behind it.
$sql = "select * from aTable where aColumn like '%".$searchedKeyword."%'";
If I search for like Greg's icecream the ' will break the script. Also, I'm guessing if I search for something like 1' or ID>0 my script will have a false effect.
What is the common solution here? Do you usually filter away undesired characters, or is there maybe some method or similiar built-in to php?
You can us PDO and prepared statements to prevent SQL injection.
http://php.net/manual/en/pdo.prepared-statements.php
$searchedKeyword = "mykeyword";
//Database details
$db = 'testdb';
$username = 'username';
$password = 'password';
//Connect to database using PDO (mysql)
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db, $username, $password);
} catch (PDOException $e) {
var_dump("error: $e");
}
//Prepared SQL with placeholder ":searchedKeyword"
$sql = "select * from aTable where aColumn like '%:searchedKeyword%'";
$sth = $dbh->prepare($sql);
//Bind parameter ":searchedKeyword" to variable $searchedKeyword
$sth->bindParam(':searchedKeyword', $searchedKeyword);
//Execute query
$sth->execute();
//Get results
$result = $sth->fetchAll(); //fetches all results where there's a match

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

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

PHP query single line from database

I'm having a problem echoing a single line from a sql query. I'm still pretty new at this but I can't figure it out at all.
I have a page titled "listing.php?id=7"
Inside the page is this script:
<?php
mysql_connect("localhost", "user", "pass");
mysql_select_db("table");
$query = "SELECT * FROM vehicles WHERE id='$id'";
$result = mysql_query($query);
while($r = mysql_fetch_array($result))
{
$year = $r["year"];
$make = $r["make"];
$model = $r["model"];
$miles = $r["miles"];
$pricepay = $r["pricepay"];
$pricecash = $r["pricecash"];
$transmission = $r["transmission"];
$color = $r["color"];
$vin = $r["vin"];
echo "$year $make $model $miles $pricepay $pricecash $transmission $color $vin<br />";
}
?>
The problem lies within "WHERE id='$id'". When I use a var, it displays nothing, but if I manually make it my ID number, example 7, it works fine. What's am I doing wrong?
if
SELECT * FROM vehicles WHERE id=7
works but
SELECT * FROM vehicles WHERE id='$id'
doesn't work
then get ride of the quotes around $id
So
SELECT * FROM vehicles WHERE id=$id
The quotes are turing $id into a string comparison - which won't work if the column type is integer.
Even better, use PDO. Create the connection:
$db = new PDO("mysql:host=localhost;dbname=someDBname", 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
but do it in just one script, preferably in a singleton or somesuch. This has many advantages, including placing all database passwords in one file (which is easier to secure) and reducing the possibility of typos in the hostname, database name, username or password causing the connection to fail. Use it as:
try {
$query = $db->prepare(
"SELECT year, make, model, miles, pricepay,
pricecash, transmission, color, vin
FROM vehicles WHERE id=?"
);
$query->execute(array($_REQUEST['id']));
while ($row = $query->fetch(PDO::FETCH_NUM)) {
echo implode(', ', $row);
}
} catch (PDOException $exc) {
echo "Query failed.";
}
This uses a prepared query, which is not vulnerable to SQL injection. It also does away with "or die".
In case you haven't seen singletons, here's an example:
class DB {
private static $db;
static function open() {
if (! isset(self::$db) ) {
self::$db = new PDO('mysql:host=hostName,dbname=dbName', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$db;
}
}
Then, whenever you need a connection, just call DB::open(). If you need to connect to multiple hosts, store PDOs in an associative array within DB, rather than DB::$db. In this case, you could put the connection information in the DB script, or put it in a separate configuration file that DB parses.
Take your original code and add this line before the query:
$id = (int)$_GET['id']; // Sanitize Integer Input
And change your query as others suggested to remove the quotes:
$query = "SELECT * FROM vehicles WHERE id=$id";
I am assuming your id is a normal mysql auto_increment which starts at 1. That means if `$_GET['id'] is anything but a number, it will come back as 0 and thus not match anything in the database.
$query = sprintf("SELECT * FROM vehicles WHERE id=%d", mysql_real_escape_string($_GET['id']));
$result = mysql_query($query);
I hope you don't have register globals on which means you should use $_GET['id'];
You can't put quotes around the id field if it's an int in your table
Use mysql_real_escape_string to prevent sql injection

Categories