Comparing input data with data queried from database - php

So when I tried to get one random row in database and store it into variables, it seems like I cannot reuse those variables for my next sql query as I was tried in these lines.
First I get one random row in database and store it into variables for later use
$mysqli = new mysqli($hostname, $username, $password, $dbname, $port) or die(mysqli_error($mysqli));
$sqlcompare = "SELECT * FROM questions order by rand() limit 1";
$result = mysqli_query($mysqli, $sqlcompare);
$row = mysqli_fetch_row($result);
$pos = $row[0];
$word = $row[1];
$pos is the id of that row $word is the data of that row.
Then I get user input and checking the database if there is a row both have the same id with $pos and the input word is the same as that row
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word = $input AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
if (isset($_POST['compare'])) {
if (mysqli_num_rows($sqlresult)>=1) {
echo "Found that input";
} else {
echo "Not found";
}
}
When I tried to retrieved word from database directly from user input, which only have one condition, the code work perfectly but when I add id condition in, it not working anymore. Any idea where I screw thing up?
Edit note: I just tried to echo $pos and $word and it work perfectly but somehow when I tried to put $pos varibale into sql to query, it does not working.

Use like instead of ( = ).
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word LIKE '%".$input."%' AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
Mysql Like docs

Related

Selecting from database WHERE somefield contains one of the value

I have one straight forward script that returns user data if access code is correct.
$sql = "SELECT * FROM users WHERE access_codes = '$CODE' ";
$rs = $mysqli->query($sql);
$rows = mysqli_num_rows($rs);
if ($rows == 1) {
//CODE IS FOUND, RETURN USERNAME AND PASSWORD
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
mysqli_close($mysqli); // Closing Connection
header("Location: http://GOTONEXTPAGE.COM");
die();
} else {
//CODE IS NOT FOUND
mysqli_close($mysqli); // Closing Connection
exit;
}
It works fine, if access_codes contains only 1 value.
But what i want to achive is that access_codes can contain several codes, separated with space ex: 123456 654321 0101020304.
And i could still retrive userdata if ANY of these codes is found.
Can i do this with query, or i need to work around with php?
Regards
M
It would be best if you normalized the schema. Make a table of access codes where there's one row for each combination of userID and access_code. Then you can use a JOIN between this table and the users table to get the users with a particular access code.
If you can't redesign, you can use a regular expression:
$sql = "SELECT * FROM users WHERE access_code RLIKE CONCAT('[[:<:]]', ?, '[[:>:]]')";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $CODE);
$stmt->execute();
[[:<:]] and [[:>:]] match word boundaries, so this will only match when the code is a whole word in the column.
$codes = "123456 654321 0101020304";
$expCodes = explode(" ", $codes);
$code = implode("', '", $expCodes);
$sql = "SELECT * FROM users WHERE access_codes IN ('{$code}') ";
// do your query

retrieve text from different rows from same column by searching in database table

I want to search in a database table for a particular word and want to retrieve a text from other column in the same row and there may be more than one rows where that word may exist, so i want all those rows where that word is.
i am using this code
$found = 'world';
$sql = "SELECT file_id FROM hello WHERE $field = '$found'";
$result = mysql_query( $sql);
$row = mysql_fetch_array($result);
while($row)
{
echo $row['file_id'];
}
so my problem here is in database table i have only 5 rows and there are only 2 possible file_id to be printed after the code, but this while loop goes to infinite.
Thanks in advance
The quick fix is this:
$found = 'world';
$sql = "SELECT file_id FROM hello WHERE field = '$found'";
$result = mysql_query( $sql);
while($row = mysql_fetch_array($result)) {
echo $row['file_id'];
}
But there are quire a lot other things to be corrected:
use the mysqli extension, the mysql extension is deprecated
you should use prepared statements to prevent sql injections
you must add error checking and handling
...
if you are starting a project use PDO
$db new PDO('mysql:host=localhost dbname=foo', 'user', 'password');
$sql = 'SELECT file_id FROM hello WHERE field = ? ';
$stmt = $db-prepare($sql);
$stmt->bindValue(1, $word);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $item){
echo $item['key'];
}

Why isn't this script working? (odd/even)

I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()

Android Mysql - too many results

I've been struggling with this problem for a couple of days and can't make any progress...
I'm trying to get just ONE result from my database but on contrary I'm getting the whole table : (
php:
{
$connect = #mysqli_connect ($host, $username, $pass, $dbname)
OR die ('Could not connect to MySQL');
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$key."='".$key_value."'";
$r = #mysqli_query ($connect, $q);
while ($row = mysqli_fetch_array($r))
$output[]=$row;
print(json_encode($output));
}
I think there's no need to show you my android code for that since the data is received well (also updating tables works fine) ... all i want is to get that ONE result from my DB.
When simply navigating to this file on the browser there's no problem obviously...
Thanks in advance, cheers
You are doing something like where 1 = 1 and that is always true. You are not naming your column. You are replacing that with a number.
try this (unverified):
"SELECT * FROM ".$table." where id='".$id."'";
If you want to get just the first row of the results, then you have two options:
include LIMIT in your query (preferred solution)
SELECT * FROM ".$table." where ".$id."='".$id."' LIMIT 1"
don't loop to get all the data, simply read the first row and return it.
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$id."='".$id."'";
You're assigning $key and $key_value but then using $id.
you are setting your condition to where ".$id."='".$id."'";, so, if you pass id=1, that will mean: WHERE 1=1, and that is always true. that's why it's returning all the records.

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