mysql query fails if name has more then 1 words - php

I began to create a website for my small real estate business.
I played a bit with functions http://www.php.net mysql and I managed to make a page accessed via AJAX and returning html content for the search engine.
I have a database already populated with apartments and houses
The problem is that if the apartment name is "apartment" I return html content if "apartment with 3 rooms" it no longer write anything.
I do not understand where I was wrong:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>

you should know if you "played" with php.net that mysql_* functions are deprecated and are no longer maintained. It's a red box on top of the page informing you that.
you have a big MySQL injection hole there, you are not escaping $string at all
your problem is that you are not adding quotes to $string like: '$string'
you should stat using PDO to get rid of the bad code and SQL Injections holes.
you can wrap those 2 selects into a single select:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
since you are already building that website you can start moving to PDO, read this tutorial, your code will be more like this:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>

try:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
and remember to always sanitize user input before passing it to sql to avoid sql injections.

Your first query should be:
$query = "select * from houses where name like $search% limit 1";

Strings need to be quoted in queries. Also, this is vulnerable to MySQL injection, make sure to escape $search with mysql_real_escape_string. Or even better yet use MySQLi or PDO instead of the old mysql_ functions.
$query = "select * from houses where name=$search limit 1";
Should be:
$query = "select * from houses where name='$search' limit 1";
Although you REALLY need to escape $search because it came from a user, even if they aren't malicious, any search queries with a single quote in it will break;
$search = $_GET['selected'];
Should be:
$search = mysql_real_escape_string($_GET['selected']);
(Anybody have the copy paste handy with the links to tutorials for MySQLi/PDO and such?)

Related

Error undeclared variable when select using limit

I have an error in my script select MySQL with limit. it said
Gagal ambil data:Undeclared variable: $st
this is my script :
include'../konekdb.php';
if(empty($_GET[start]))
{
$st="0";
}
else
{
$st=$_GET[start];
}
$query = 'SELECT * FROM pelanggan LIMIT $st,5';
$ambildata = mysql_query($query);
if(!$ambildata)
{
die('Gagal ambil data:'.mysql_error());
}
include'tabel_pelanggan.php';
mysql_free_result($ambildata);
mysql_close($koneksi);
$query2 = mysql_query("SELECT * FROM pelanggan");
$num = mysql_num_rows($query2);
$hal = ceil($num/5);
echo "Halaman :";
for($i=1;$i<=$hal;$i++){
$page=$i-1;
echo "[][<a href=$_SERVER[PHP_SELF]?start=$page>$i</a>][]";
}
can you help me? thanks before :)
You have an error with you $_GET, you're missing the quotes around the key name.
Your $_GET,
$st=$_GET[start];
What it should be,
$st = $_GET['start'];
Edit 1
You shouldn't be using MySQL now as it is deprecated. Either start using MySQLi or PDO, you should also look in to prepared statements.
Edit 2
Also don't forget to change your if statement too.
From
if(empty($_GET[start]))
To,
if(empty($_GET['start']))
Edit 3
Your query needs to use double quotes or if you want to use single quotes you need to close the single quotes then add the variable on.
From,
$query = 'SELECT * FROM pelanggan LIMIT $st,5';
To,
$query = 'SELECT * FROM pelanggan LIMIT ' . $st . ',5';
Or,
$query = "SELECT * FROM pelanggan LIMIT {$st},5";

Selecting row where field = value error

Can you explain me why my code isnt working? Ive been thinking about it for a while and I cant find it. obviously I want to print some columns from rows where column F1 is equal to user's username.
$db = JFactory::getDBO();
$user = JFactory::getUser();
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$user->username;
$db->setQuery($query);
$result = $db->query();
while($row = mysqli_fetch_object($result))
{
print $row->F1;
}
It works when I remove condition from select command and I cant figure out how to make it work with it
$query = "SELECT * FROM qwozh_visforms_1";
Now Im getting this error:
UNKNOWN COLUMN 'ADMIN' IN 'WHERE CLAUSE' SQL=SELECT * FROM
QWOZH_VISFORMS_1 WHERE F1 = ADMIN RETURN TO PREVIOUS PAGE
Thanks
All it takes if a quick read of the Joomla documentation. The following is the same as your query but making full use of Joomla's up to date database class:
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select(array('*'))
->from($db->quoteName('#__visforms_1'))
->where($db->quoteName('F1') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$results = $db->loadObjectList();
// Display the results
foreach($results as $result){
// echo what you want here
}
Note, I've used the prefix #__ rather than manually defining qwozh, assuming your table belong to a Joomla extension.
I know PHP and MySQL, but not Joomla. But the problem is that your username needs to be quoted because it is probably a string.
Try this:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '{$user->username}'";
or
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$db->quote($user->username);
You need to wrap the name in quotes:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '".$user->username . "'";
As pointed out in the comments my answer has a pretty bad quality, you may want to look at prepared statements, expecially using bindParam, which takes care of quotes for you and protects you agains SQL injection attacks.
Unfortunately I cannot suggest you Joomla based approach since I never used it, somebody else can suggest you a more appropriate solution.

How WHERE clause works when inserting php variables

I am having problems trying to get these queries with a WHERE clause to work. I have two tables which look like this :
What I am trying to do is return the genre that each film has. At the moment no data is returning at all from what I can see. Here are the two queries:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
$row_get_genre = mysql_fetch_assoc($get_genre);
$totalRows_get_genre = mysql_num_rows($get_genre);
$genre_id = $row_get_genre['id_genre'];
mysql_select_db($database_fot , $fot);
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
$totalRows_genre = mysql_num_rows($genre);
PHP with content area. I fairly new to PHP so any help would be appreciated.
<?php do { echo $genre['genre']; } while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Update: I am now able to get first genre but not second it just echos the first one twice and I have tried but still no luck:
do {do { echo $row_genre['genre']; } while($row_genre = mysql_fetch_assoc($genre));} while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Avoiding the fact that you're using a deprecated way to establish connection and interact with MySQL, what you're doing is getting a single relation genre-film and then getting the row of the genre that matches. You should surround part of your code with a while that executes while it's still genres of the film with id. Something like:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
while($row_get_genre = mysql_fetch_assoc($get_genre)){
$genre_id = $row_get_genre['id_genre'];
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
// You should do whatever you want to do with $row__genre here. Otherwise it will be cleared.
}
I must insist this is a deprecated and insecure way of communication with a MySQL Database. I recommend you read about MySQLi or PDO extensions.
MySQLi: http://www.php.net/manual/en/book.mysqli.php
PDO: http://www.php.net/manual/en/book.pdo.php

GET request - unable to do a SELECT statement from DB

I will be sending a request to the PHP code through a GET request. it will have several parameters passed. I will be using these parameters in the WHERE clause of my select statement.
GET REQUEST
http:// localhost/server/person.php?Id=1&age=12&hieght=100
PHP code
<?php
$connection = mysql_connect("localhost","user","pwd");
if (!$connection )
{
die('FAIL: ' . mysql_error());
}
mysql_select_db("db", $connection );
$result = mysql_query("SELECT * FROM Person where hieght='$_GET[hieght]");
$num_rows = mysql_num_rows($result);
?>
i think my PHP code is wrong. I am not sure if this is the way to grab variables from a GET request.
To get a variable from $_GET use, as an example to get height from $_GET array you can write
$height=$_GET['height'];
so you can write
$result = mysql_query("SELECT * FROM Person where hieght='".$hieght."'");
or you can write
$result = mysql_query("SELECT * FROM Person where hieght='".$_GET['height']."'");
Update:
Use mysql_real_escape_string to prevent sql injection, like
$height=$_GET['height'];
$result = mysql_query("SELECT * FROM Person where hieght='".mysql_real_escape_string($hieght)."'");
or
$result = mysql_query("SELECT * FROM Person where hieght='".mysql_real_escape_string($_GET['height'])."'");
$result = mysql_query("SELECT * FROM Person where hieght='".$_GET['hieght']."'");
A good debug technique when you are feeling your your is to put the SQL into a string
that you can log and see if it is what you expected.
Using mysql_error() after the query may have given you a hint too...
$sql = "SELECT * FROM Person where hieght='".$_GET['hieght']."'";
$result = mysql_query($sql);
#Not for production code, but handy while learning - error goes into web server log.
error_log("SQL=$sql, error=".mysql_error());
You should be parsing input like that for injections:
<?php
$myHeight = mysql_reaL_escape_string($_GET['height']);
$connection = mysql_connect("localhost","user","pwd");
if (!$connection )
{
die('FAIL: ' . mysql_error());
}
mysql_select_db("db", $connection );
$result = mysql_query("SELECT * FROM Person where height=$myHeight");
$num_rows = mysql_num_rows($result);
?>
Secondly, you should also be using the PHP PDO object rather than the old mysql_query etc.
Use this
$height = $_GET['hieght'];
$result = mysql_query("SELECT * FROM Person where hieght='$height'");
Instead of
$result = mysql_query("SELECT * FROM Person where hieght='$_GET[hieght]");
Note that with this code it is very likely to be victim of sql
injection
you may also wanna use this concat:
mysql_query("SELECT * FROM Person where hieght='".$_GET['hieght']."'");

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories