Cant use LIKE to extract data from mysql using php - php

I have been battling with this code for some time and could do with some advice. I have created a mysql database of computer games and a simple search box and button within a form. If I type in any key word regarding the name of the game or its description, php should echo the results in a drop down (since there might be more than one 'hit'). At present, I'm just showing the results at the bottom of the page. My query happily runs the else statement and shows me all the games on offer, but I get no results when I type in the search criteria and no error messages. print_r($q) also draws a blank. What's going wrong?
NB. I'm not too worried about code injection at this point - 1 baby step at a time! Many thanks
<!DOCTYPE HTML>
<HTML>
<head></head>
<?php
//Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "Secret";
$dbname = "gaming";
//Create connection
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if (!$conn){
die("Connection failed: " .
mysqli_connect_error());
}
if(isset($_REQUEST['submit'])){
$search=$_POST['search'];
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
$q=mysqli_query($conn,$sql);
}
else{
$sql="SELECT* FROM gamestbl";
$q=mysqli_query($conn,$sql);
}
?>
<body>
<form method="post">
<table width="200" border="1">
<tr>
<td>Search</td>
<td><input type="text" name="search" value="" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<table>
<tr>
<td>Game ID</td>
<td>Game Name</td>
<td>Game Description</td>
<td>Game Genre</td>
<td>Game Price</td>
</tr>
<?php
print_r($q);
while($res=mysqli_fetch_array($q)){
?>
<tr>
<td><?php echo $res['game_id'];?></td>
<td><?php echo $res['game_genre'];?></td>
<td><?php echo $res['game_name'];?></td>
<td><?php echo $res['game_description'];?></td>
<td><?php echo $res['game_price'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($conn);
?>

Change
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
For
$search = mysql_real_escape_string($search); // Prevent from injection
$sql = sprintf("SELECT * FROM gamestbl WHERE concat(game_name, game_description) LIKE '%s'", '%' . $search . '%');
sprintf is the better way to add variable in a string and concat will make your sql shorter by avoiding "OR".

Instead of '%.$search.%' you have to use '%$search%' (notice skipped dots). Or even better (in my opinion) '%".$search."%'.
Currently you are passing dots in your query so instead of searching for example you are asking database for rows with .example. in name or description.

Related

Data inserted through PHP does not appear in phpMyAdmin

I have a simple PHP page that posts to a DB. I actually only use it for debugging because the real app receives posts from an Arduino:
SamplePost.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="data_post.php" method="post">
<table style="text-align: left; width: 100%;" border="0"
cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td>Name(Temp):</td>
<td><input name="username" type="text"></td>
<td></td>
</tr>
<tr>
<td>Age(co2):</td>
<td><input name="age" type="text"></td>
<td></td>
</tr>
<tr>
<td>UVIndex:</td>
<td><input name="uvindex" type="text"></td>
<td></td>
</tr>
<tr>
<td>MQ2:</td>
<td><input name="mq2" type="text"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit"></td>
</tr>
</tbody>
</table>
<br>
</form>
</body>
</html>
I recently used it to debug because I was having issues with the Arduino app not posting since 20 days ago. Oddly enough I discovered the DB username I had in the PHP was incomplete. Odd because it has been posting for years and I honestly don't remember having changed the DB username in the PHP, but whatever. So this is what it posts to:
data_post.php
<?php
$user = 'myusr';
$password = 'mypwd';
$server = 'localhost';
$database = 'mydb';
$pdo = new PDO("mysql:host=$server;dbname=$database", $user, $password);
$username=$_POST['name'];
$age=$_POST['age'];
$uvindex=$_POST['uvindex'];
$mq2=$_POST['mq2'];
$sql = "INSERT INTO example (name,age,uvindex,mq2,beer) VALUES (:username, :age, :uvindex, :mq2, 'NO')";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":age", $age);
$stmt->bindParam(":uvindex", $uvindex);
$stmt->bindParam(":mq2", $mq2);
$result = $stmt->execute(array(':username'=>$username, ':age'=>$age, ':uvindex'=>$uvindex, ':mq2'=>$mq2));
if($result) {
echo "Your text has been posted";
}// end if
else {
echo '0 results';
}// end else
file_put_contents("arduinopost.txt",$username);
?>
So after I corrected the DB username in code, I used the SamplePost.html and it worked because I got my success message from the PHP if-else and I refreshed my DB read file and the post appeared:
query.php
<html>
<body>
<?php
$servername = "localhost";
$username = "myusr";
$password = "mypwd";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM example where id > (SELECT MAX(id) - 20 FROM example)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id=" . $row["id"]. ". Temp=" . $row["name"]. ". CO2PPM=" . $row["age"]. ". UVIndex=" . $row["uvindex"]. ". MQ2R=" . $row["mq2"]. ". Timestamp=" . $row["timestamp"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
But the weird thing is that when I look for that entry in the DB via phpMyAdmin, it's simply not there. But I can see the data printed from the query.php on my screen and I've refreshed it multiple times, it's still there...
How can data be in a PHP page that reads from the DB, but not in the DB?
I added the screenshot of phpmyadmin, where are you can see, they records are ordered by descending timestamp, so i should be seeing the latest records, right?
As a side note, the arduino app started posting to the data_post.php page again successfully and I can now see the latest record in my query.php page but I cannot see the records in the phpmyadmin. Im thinking this is gonna turn up to be something silly but i was worried whatever the cause is, that it might be related to the arduino not being able to post. But at least now posting is working again.

PHP - HTML form, connecting with select box options

For this project, I have an upload page for the user to upload a CSV file where it is inserted into a DB in one single staging table. From there, some things are split and also inserted into separate tables. Each CSV has 2 to 8 rows, and each row has 228 fields, so there are 228 columns in my staging table.
Once uploaded, the user can go to a page (userSelect.php) and use dropdowns to help select a work order to view where it will be displayed in multiple tables.
The upload/insert works great, and the dropdowns are populating with the elements from the database properly but I can't seem to connect the selections to the table page.
For instance, if the user selects the "Work Order Packet" dropdown and chooses 'February Zone B1', I want this to show links with any record from the database that has this work order packet name. Then, once they select the record they want, I want the display.php page to fill all the tables with the 228 elements from that specific record, using the id I assume.
I have the code for these two pages below. The userSelect page does not currently have any code for showing the database records as links either so i'm hoping to figure out how I can show those and then use the one the user selects to fill the tables on the display page.
userSelect.php
<form method="post" action="display.php" enctype="multipart/form-data">
<input type="submit" name="submit" value="Confirm" >
</form>
<?php
$server = "localhost";
$user = "root";
$pw = "root";
$db = "uwsTest";
$connect = mysqli_connect($server, $user, $pw, $db);
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo'success!';
}
?>
<label>Select Work Order Packet:</label>
<select name="workOrderPacket">
<?php
$sql = mysqli_query($connect, "SELECT workOrderPacket FROM staging;");
while($row = $sql->fetch_assoc()){
echo "<option >" . $row['workOrderPacket'] . "</option>";
}
?>
</select>
<label>Select Work Order ID:</label>
<select name="WorkOrderNumber">
<?php
$sql2 = mysqli_query($connect, "SELECT workOrderNum FROM staging;");
while($row2 = $sql2->fetch_assoc()){
echo "<option>" . $row2['workOrderNum'] . "</option>";
}
?>
</select>
display.php
<?php
if(isset($_POST['submit']))
{
while($row = mysqli_fetch_array($result1)){
?>
<!--Qa Table-->
<table>
<tr>
<th colspan="2">Qa/Qc CheckList</th>
</tr>
<tr>
<td>Service Address Correct</td>
<td><? echo $row['serviceAddress'];?> </td>
</tr>
<tr>
<td>Service Loc Correct</td>
<td><? echo $row['serviceLoc'];?> </td>
</tr>
<tr>
<td>Meter Number Correct</td>
<td><? echo $row['meterNumber'];?> </td>
</tr>
<tr>
<td>Meter Manufacturer Changed</td>
<td><? echo $row['meterManufacturer'];?> </td>
</tr>
<tr>
<td>Meter Type Changed</td>
<td><? echo $row['meterType'];?> </td>
</tr>
<tr>
<td>Meter Model Changed</td>
<td><? echo $row['meterModel'];?> </td>
</tr>
<tr>
<td>Low Register Correct</td>
<td><? echo $row['registerCorrect'];?> </td>
</tr>
<tr>
<td>High Register Correct</td>
<td><? echo $row['registerCorrect'];?> </td>
</tr>
</table>
UPDATE - unfinished SQL query for display.php:
$query1 = "SELECT * FROM staging WHERE StageID = ;";
$result1 = mysqli_query($connect,$query1);
You will need to update your SQL statement to filter the associated results.
SELECT workOrderNum FROM staging WHERE workOrderPacket = '.$_REQUEST["workOrderPacket"] ';

Displaying SQL data in HTML form

I wrote following code in PHP to get the details from the mysql table but I dont know how to display them in HTML form.
<?php
$servername = "localhost";
$username = "root";
$password = "icsk";
$dbname = "yusuf";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT dsl, Fname, Lname, Cid, pack FROM homereg";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['dsl']. " " . $row['Fname']. " " . $row['Lname']. " " . $row['cid']. " " . $row['pack'] ."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The above code displays the data on the webpage with the help of echo but i want it to be displayed in form.
HTML form has following code:
<form method="POST" name = "frm" action="homerenew.php">
<div align="center">
<table border="1" width="425">
<tr>
<td width="223"><font face="Georgia"><b>Subscription Number</b></font></td>
<td width="186"><input type="text" name="T1" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Your Current Pack</b></font></td>
<td width="186"><input type="text" name="T2" size="20"></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Renewal Options</b></font></td>
<td width="186"><select size="1" name="D1">
<option value = "1 Month">1 Month</option>
<option value = "2 Months">6 Months</option>
<option value = "1 Year>1 Year</option>
</select></td>
</tr>
<tr>
<td width="223"><font face="Georgia"><b>Balance Payable</b></font></td>
<td width="186"><input type="text" name="T3" size="20"></td>
</tr>
</table>
</div>
<p align="center"><input type="submit" value="Renew" name="B1">
<input type="reset" value="Reset" name="B2"></p>
</form>
I am new to PHP connectivity that is why little confused. Help will be greatly appreciated. Thank you
First of all you need to have .php extension of the page containing your HTML form.
After fetching data from database you could set it into form element like
<input type="text" name="T1" size="20" value="<?php echo $row['dsl'];?>">
I would recomend using a templating engin similar to PHPTal. You write your html page as an .xhtml file that contains tal: tags that are used by the template engine to insert your php values. Install instructions, example of use.
The benfit of using a template engine is you can remove all html content from your scripts and leave the display logic in the xhtml file. The php code just gathers the data and assigns it to labels your template knows about.
You can get all rows as an array and assign it to a variable name in the template object in php. That variable name is then used in the xhtml file to repeat rows in your table (or any other element).
Php:
<?php
require_once 'PHPTAL.php';
$rows = getMyDBRows();
// create a new template object
$template = new PHPTAL('my_template_file.xhtml');
$template->rows = $rows;
// execute the template
try {
echo $template->execute();
}
catch (Exception $e){
echo $e;
}
Xhtml rows section with example of repeating each row, inserting element contents, setting attributes and using a conditional statement to only display the input field for the row with index 1. Repeat method can be used for options in selects and conditional check for setting selected attribute. Phptal requires strict xhtml structure any errors in your xhtml and the page will return an error identifying where there was a problem.
<tr tal:repeat="row rows">
<td tal:content="row/dsl"><\td>
<td tal:content="row/fname"><\td>
<td><input name="lname" tal:attributes="value row/lname, style php: repeat.row.id EQ 1?'display:inline-block':'display:none" tal:content="row/lname"></input>
......
<\tr>

Read and Write to SQL Database

I have the script that will write info to the database, but how can I have it print the variable "time" from the database after it updated the same query based on the email entered to write to database? This is for use with JSON.
<?php
if(!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'casaange_testapp';
$dbpass = 'testapp1';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('casaange_volunteertest');
$email= $_POST['email'];
$time= $_POST['time'];
$sql = "UPDATE users SET time= '$time' WHERE email = '$email'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
if($retval){
$response["success"] = 1;
$response["message"] = "Update successful!";
die(json_encode($response));
}
//echo '{"success":1, "message":"Time added!"}';
mysql_close($conn);
}
else
{
?>
<form method="post" action="timeinsert.php">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Email:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td width="100">Time:</td>
<td><input name="time" type="text" id="time"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
I think what you want to know is whether the UPDATE query actually changed the value in the database?
You can use mysql_affected_rows() see how many rows changed as a result of your query - in your case it will be either 1 or 0.
If you need to return the time that you just put into the database, you can query the value that actually went into the database by selecting it back out with the email address as the key.
A few general observations about your code, if I may:
You must escape that POST data before putting it into an SQL query
like that. At best it'll be a source of bugs, worst a massive
security hole.
If you're writing new code, as you appear to be here, you should
consider using the newer MySQLi or PDO_MySQL extensions instead of
the old MySQL calls.
You can use json_encode to turn an associative PHP array into a JSON
object, instead of building a JSON string yourself.

Display search criteria in search box while results are being displayed with PHP

I have a search form and am displaying the results on the same page as the search form. So, before a search takes place, all the possible results are visible. Once a keyword is entered into the form, the results are only those that contain the keyword. I would like the form to display the keyword that was entered into the form when the results are displayed. I have tried multiple things and my latest attempt is to enter into various parts of the form, but with no luck. I have searched multiple tutorial sites and am not finding this particular request to be addressed. Can any of you help me to get the search criteria to remain in the search box when the results are displayed? Here is the code I am using:
<html>
<body>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
function getRecords($query) {
$con = mysql_connect("localhost", "movie", "moviepw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("movies", $con);
$result = mysql_query($query);
return $result;
}
function buildQuery() {
$keyword = $_GET['keyword'];
$sql = "SELECT * from table1 WHERE (movie_title LIKE '%$keyword%'
OR movie_description LIKE '%$keyword%')";
return $sql;
} ?>
<form action="movie_form.php" method=get>
<fieldset>
<legend>Movies</legend>
<label for="keyword">Search</label>
<input id="keyword" name="keyword" />
<input type=submit name=submit value=Search />
<? echo $keyword ?>
</fieldset>
</form>
<?
$query = buildQuery();
$records = getRecords($query);
while($row = mysql_fetch_array($records)){ ?>
<table>
<tbody>
<table border='1'>
<tr>
<td><?= $row['movie_title']; ?></td>
<td><?= $row['movie_rating']; ?></td>
<td><img src="<?= $row['movie_image'];?>"></td>
<td><?= $row['movie_description']; ?></td>
<td>Return to Search</td>
</tr>
<? } ?>
</tbody>
</table>
</body>
</html>
Add the "value" attribute to your "keyword" form input. Something like this:
<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>"/>
Also, move the setting of $keyword out of the buildQuery() method so that it will be available when your form is output. You could put it right after error_reporting is set:
<?php error_reporting (E_ALL ^ E_NOTICE);
$keyword = rtrim($_GET['keyword']);
?>
Finally, this code is vulnerable to sql injection. Check this out:
How can I prevent SQL injection in PHP?

Categories