The result of my search isn't appearing using php code - php

<html>
<body>
<form action="checkorderstatus.php" method="post">
<input id="search" type="text" placeholder="Type here">
<input id="submit" type="submit" value="Search">
</form>
</body>
</html>
<?php
require_once 'loginorder.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) {
die($conn->connect_error);
}
if (isset($_POST['submit']));
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = $conn->query($query); //run the query and get the result
if (!$result) {
die($conn->error);
}
$rows = $result->num_rows;
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = mysqli_query($conn, $query);
($row = mysqli_fetch_row($result)); {
echo $row['1'];
print_r($row);
}
?>
I'm trying to display the status description when the statusid is entered into the search but it's not displaying anything other than Array ( [0] => product is in transit )
and I'm getting 3 errors
Notice: Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 20 Notice:
Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 28 Notice:
Undefined offset: 1 in C:\wamp64\www\groupproject\checkorderstatus.php
on line 36

Problems
There are a host of problems with your code as it stands...
Forms posted to PHP use the name attribute in the $_POST superglobal
Therefore you are effectively not submitting anything when you submit your form
Add the name="..." attribute to each of your form elements to fix this
Your if statements are by and large redundant
Not least because you don't post anything as per point 1
You should be using prepared statements for user generated input to protect your database from attack and or corruption
Your code is generally confusing and not laid out very well
I'm not sure what half of your brackets, ifs and function calls are supposed to be doing
The notice you're getting is because you never set $search in your PHP
Solution
N.B
This assumes that all of the code is in the one file [`checkorderstatus.php] and that it submits to itself.
Additional note:
I'm not sure that LIKE '%...% is the best solution here. It appears you're looking for id which, presumably (?) is a number? In which case I would simply user:
WHERE deliverystatus.statusid = SEARCH_ID
The below code follows that premise. If however you are indeed in need of LIKE then you should update the query like:
WHERE deliverystatus.statusid LIKE ?
and update the search term in the code:
$search = "%".$_POST["search"]."%";
Updated HTML form
<form action="checkorderstatus.php" method="post">
<input id="search" name="search" type="text" placeholder="Type here">
<input id="submit" name="submit" type="submit" value="Search">
</form>
Using mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli ($hn, $un, $pw, $db);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("i", $search); // Bind search valus as an integer (use "s" if it's a string)
$query->execute(); // Execute the query
$query->store_result(); // Store the result
$query->bind_result($status_description); // Bind "statusdescription" to a varaible
while($query->fetch()){ // Loop through result set
echo $status_description}."<br>"; // Echo each match to a newline
}
}
Using PDO
$pdo = new pdo(
"mysql:host={$hn};dbname={$db}", $un, $pw,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$search]); // Execute the query binding search as the parameter
while($result = $query->fetchObject()){ // Loop through result set
echo $result->statusddescription."<br>"; // Echo each match to a newline
}
}

Related

Getting error when trying to fetch data from MySQL using PHP

When trying to fetch data from a Mysql database using PHP, the following code gets a message:
Getting error:
undefined variable result.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
echo <<<_END
<form action="fetchdata.php" method="post"><pre>
Enter Country <input type="text" name="field">
<input type="submit" value="Display Records">
</pre></form>
_END;
if (isset($_POST['field'])) {
$field=$_post($conn,'field');
$query="SELECT * FROM customers WHERE Country = '$field'";
$result=$conn->query($query);
if (!$result) die($conn->error);
}
$rows = $result->num_rows;
Instead of
$field=$_post($conn,'field');
Maybe you mean
$field=$_POST['field'];
Additionally you use $result at the end, even when it is not defined:
$rows = $result->num_rows;
Also you never output any data and print it. You just store it in variables.
In any case: What you are doing there by writing form data directly into a query string, is dangerous. I recommend you to use PDO together with Named Parameters. Also maybe read up about SQL injections.
Here is another stackoverflow question with a nice answer, regarding SQL injections. It includes both PDO and mysqli: https://stackoverflow.com/a/60496/6637731
Without telling how request to this code is done, one guess is that isset($_POST['field']) returns false, hence variable $result is never defined but you use it anyway below in $result->num_rows.
You made a mistake in the below line. It should be
$field=$_POST['field'];
not
$field=$_post($conn,'field');

Coding errors in PHP and MYSQL [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I followed a youtube tutorial which teaches you how to create an edit and delete data page for PHP and MYSQL but for some reason why code isn't working. Two error messages showed up:
Notice: Undefined variable: _Get in C:\Users\siaw_\PhpstormProjects\Report Page\modify.php on line 6
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\Users\siaw_\PhpstormProjects\Report Page\modify.php on line 8
I followed the tutorial exactly the way it is... I have very limited knowledge on PHP & MYSQL so please figure out the error on line 6 and 8?
Here is the code:
<?php
include 'connect.php';
if(!isset($_POST['submit'])) {
$q = "SELECT * FROM people WHERE ID = $_Get[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
<h1>You Are Modifying A User</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description <input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify" />
</form>
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE people SET `Name`='$_POST[inputName]', `Description`='$_POST[inputDesc]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User Has Been Modified";
header("Location: index.php");
}
?>
Also here is the youtube link which I used (https://www.youtube.com/watch?v=kc1bppUlqps)
You should bind properly the variables into your query
You should also sanitize your variables before using them into your query by using *_real_escape_string()
I think your page will have an error when the first isset($_POST["submit"]) condition was not met.
Sanitize your variable(s) first:
$id = mysql_real_escape_string((int) $_GET["id"]);
Bind them to your query:
$q = "SELECT * FROM people WHERE ID = '$id'";
Note that mysql_* is already deprecated and you should consider at least the mysqli_*.
But...mysql is deprecated :(
If you are interested with mysqli_*, you can check this:
First, we have to connect to your database (connection.php) using mysqli_*:
$conn = new mysqli("Host", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then for your php file where you process the $_GET["id"]:
if(isset($_POST['submit'])) {
$stmt = $con->prepare("SELECT Name, Description FROM people WHERE ID = ?"); /* PREPARE THE QUERY */
$stmt->bind_param("i", $_GET["id"]); /* BIND $_GET["id"] TO YOUR QUERY; i STANDS FOR INTEGER TYPE */
$stmt->execute(); /* EXECUTE YOUR PREPARED QUERY */
$stmt->bind_result($name, $description); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
$stmt->fetch(); /* FETCH THE RESULTS */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
/* YOUR HTML CODE HERE */
if(isset($_POST['submit'])) {
$stmt = $con->prepare("UPDATE people SET Name = ?, Description = ? WHERE ID = ?");
$stmt->bind_param("ssi", $_POST["inputName"], $_POST["inputDesc"], $_POST["id"]); /* s STANDS FOR STRING TYPE */
$stmt->execute();
$stmt->close();
echo "User Has Been Modified";
header("Location: index.php");
}
You need to put the $_GET outside, and also your $_GET syntax is incorrect, try to change :
if(!isset($_POST['submit'])) {
$q = "SELECT * FROM people WHERE ID = $_Get[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
with this one :
if(!isset($_POST['submit'])) {
$id = $_GET['id'];
$q = "SELECT * FROM people WHERE ID = $id";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}

Access denied for user 'root'#'localhost' (using password: NO)

I'm using a simple form to do a database query. The database is accessed via password which I've included in the code. I'm not sure why I keep hitting the error on the string escape and the undefined variable $query = htmlspecialchars($query);
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
The issue here is that you've invoked a mysqli object with your credentials, however, later you try to execute with the mysql_ procedural method. You don't have a connection there. You need to stick with the mysqli object. Furthermore, you should use prepared statements to handle your user input on SQL queries.
Remove these, we don't need to do sanitization for prepared statements:
//BYE!
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
Now let's use the mysqli object and OOP prepared methods. However, first we need to construct our like statements as our query's variables aren't executed, you can't concatenate %?% directly into the prepared() statement.
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
Now we can bind the parameters to our $stmt object.
$stmt->bind_param('ss', $query, $query);
Let's execute it now and get our data back.
$result = $stmt->execute();
Then we can loop:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
Edit
You also don't need to escape your column names with a backtick because:
They don't have - in the name
They aren't reserved special words in MySQL.
make sure your PHP version is below 7.0 as stated here:
http://php.net/manual/en/function.mysql-real-escape-string.php
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()

Trying to search ID and Display selected information

I have made a search box so that you can enter the product id that you wish to gain the information of. When i input data in the product id box, there are no results returned, anyone know what im doing wrong? I think that 'while ($row = mysql_fetch_array($result)) {' is wrong but not too sure as everything ive tried didn't work.
<div class="searchbox">
<form action="Search.php" method="get">
<fieldset>
<input name="search" id="search" placeholder="Search for a Product" type="text" />
<input id="submit" type="button" />
</fieldset>
</form>
</div>
<div id="content">
<ul>
<?php
// connect to the database
include('base.php');
$search = mysql_real_escape_string($_GET['search']);
$query = "SELECT * FROM Product WHERE ProductID LIKE '%{$search}%'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<li><span class='name'><b>{$row['ProductID']}</b></span></li>";
}
Don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Then you should make sure that you actually have the variable:
$search = isset($_GET['search']) ? $_GET['search'] : false;
So you can actually skip the database thing if something, somehow, fails.
if(!$search)
{
//.. return some warning error.
}
else
{
// Do what follows.
}
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM Product WHERE ProductID LIKE :search;"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':search' => $search)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$productId = $row['ProductID'];
echo "<li class='name><strong>$productId</strong></li>";
}
Oh yes, don't use the b tag, it's outdated. Use strong instead (It's even smarter to apply font-weight: bold; to .name in a separate css file.
Feel free to ask questions if anything is unclear.
remove the {} before and after $search.
should be:
$query = "SELECT * FROM Product WHERE ProductID LIKE '%$search%'";
You can use:
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
To confirm that the data is returning.

mysqli_error: updating tables (Procedural style)

I am using PHP to try and update information I have in a mysqli table. I have decided to try and use mysqli rather than mysql. Unfortunately I cant seem to find my answer anywhere because im also trying to complete it Procedural style, as I have no knowledge of OOP and all tutorials (that i have found) are in OOP.
Below is the script I have created. I have added comments to say what I think each command is doing.
<?php
DEFINE('DB_USER', 'root');
DEFINE('DB_PASS', 'password');
DEFINE('DB_NAME', 'test');
DEFINE('DB_HOST', 'localhost');
//connect to db
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_connect_error($dbc));
mysqli_set_charset($dbc, 'utf8');
//form not submitted
if(!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE people_id = $_GET[id]";//compares id in database with id in address bar
$r = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r, MYSQLI_ASSOC);//returns results from the databse in the form of an array
}else{//form submitted
$q = "SELECT * FROM people WHERE people_id = $_POST[id]";//compares id in database with id in form
$r2 = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);//returns results from the database in an array
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$hobby = $_POST['hobby'];
$id = $_POST['id'];
//mysqli code to update the database
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
//the query that updates the database
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
//1 row changed then echo the home page link
if(mysqli_affected_rows($dbc) == 1){
echo "home page";
}
}
?>
The update form
<form action="update.php" method="post">
<p>First name<input type="text" name="fname" value="<?php echo "$person[people_fname]" ?>" /></p>
<p>Last name<input type="text" name="lname" value="<?php echo "$person[people_lname]" ?>" /></p>
<p>Your age<input type="text" name="age" value="<?php echo "$person[people_age]" ?>" /></p>
<p>Your hobby<input type="text" name="hobby" value="<?php echo "$person[people_hobby]" ?>" /></p>
<input type="hidden" name="id" value="<?php echo $_GET['id'] ?>" />
<input type="submit" name="submit" value="MODIFY" />
</form>`
When I submit the form I get the following error message
Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\sandbox\update.php on line 39
I realize this is telling me the issue is with
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
So I have tried to put the sqli code in as the second parameter (i realize this is the same as putting the variable in, but it was a last resort), but it didn't seem right and still didn't work. I have also looked a php.net but couldn't work out the answer from the example they have given
Please advise, I thought this was meant to be simple?
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
You need to quote out the variables:
$update = "UPDATE people
SET people_fname = '$fname',
people_lname = '$lname',
people_age = '$age',
people_hobby = '$hobby'
WHERE people_id = '$id'";
HOWEVER
You should look into bound parameters - you're taking user input and writing it straight into your database, which means that a malicious user can do all sorts of mischief.
Have a look at the manual page for mysqli's bind_param - there are plenty of example code snippets.
Don't pass $r to mysqli_error. It accepts an optional mysql link, but not a query result anyway.
In your case, the query is executed. That evaluates to false, which is assigned to $r. The assignment evaluates to false, causing you to call die(mysqli_error($r)) with $r being false.
I think you meant to pass $dbc to mysqli_error.
Looks to me like the problem is with the database connection ($dbc). Because you are using
#mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME)
The '#' may be hiding the connection error somehow.
Also, please tell me you're doing data sanitisation in real life, right? If not, you have to run mysqli_real_escape_string() on all the POST and GET data.
you wrote
//returns results from the database in an array
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);
but you should write
//returns results from the database in an array
$person = mysqli_fetch_array(MYSQLI_ASSOC);

Categories