PHP /MYSQL Search Form Displaying Empty Results - php

Please Guys what must be wrong with this my code, I have tried to fetch the search data from my Database as follows
Students DATA As follow
Reg Number: Full Name: Faculty: Program: Level: Group.
on the HTML Search Page
<html>
<h2> Enter your matric number to connect to others studying your course </h2>
<form action="demo.php" method="post">
<b> ReG </b><input type="text" Name="find">
<input type="submit" value="Submit" />
</form>
</html>
PHP SIDE
<table border="1">
<tr>
<th>Student Full Name</th>
<th> Faculty</th>
<th> Program</th>
<th> Entry Year</th>
<th> Study Group</th>
<th> Group Members Contact</th>
<th> Group Leader Contacts</th>
</tr>
<?php
$conn=mysqli_connect("localhost", "root", "", "student");
// Check connection
if($conn=== false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$q = $_POST['find'];
if ($q == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
$sql = "SELECT * FROM study_circle WHERE matric LIKE $q ";
$result = mysqli_query($conn, $sql);
if ($result)
{
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $row['full_name'];
echo "</td>";
echo "<td>";
echo $row['faculty'];
echo "</td>";
echo "<td>";
echo $row['program'];
echo "</td>";
echo "<td>";
echo $row['entry_year'];
echo "</td>";
echo "<td>";
echo $row['study_group'];
echo "</td>";
echo "<td>";
echo $row['group_members'];
echo "</td>";
echo "<td>";
echo $row['group_leader'];
echo "</td>";
echo "</tr>";
echo "<br/>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Each time I try it it's bringing Empty results even though I have populated the database
Right now it's on my Localhost system, please anyone good person to help, am just new to Programming. I will be happy to fix this

Your code is misinterpreting what a false value means here:
if ($result)
{
//...
} else {
echo "0 results";
}
A false value in $result doesn't mean the search didn't find anything, it means the query failed with an error. To get the error, use mysqli_error:
if ($result)
{
//...
} else {
echo "There was an error: " . mysqli_error($conn);
}
In this case the error is probably a syntax error in your SQL code because you're directly concatenating user input to SQL code. This is also called a SQL injection vulnerability. There is some good information to get you started on correcting that here, including specifically how to use query parameters with the LIKE operator here. At its simplest you will want to use a prepared statement with a query parameter instead of using string interpolation like you do now.

Try adding wildcard characters to the start and end of the search string:
$sql = "SELECT * FROM study_circle WHERE matric LIKE '%$q%'";

You willl need to get the rowcount of the search data. That will gurantee if the record is there or not
Eg.
$rowcount = mysqli_num_rows($result);
and then perform if statement with it.
see code below.
<?php
$conn=mysqli_connect("localhost", "root", "", "student");
// Check connection
if($conn=== false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$q = $_POST['find'];
if ($q == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
$sql = "SELECT * FROM study_circle WHERE matric LIKE $q ";
$result = mysqli_query($conn, $sql);
$rowcount = mysqli_num_rows($result);
if( $rowcount ){
$row = mysql_fetch_array($result);
echo "<tr>";
echo "<td>";
echo $row['full_name'];
echo "</td>";
echo "<td>";
echo $row['faculty'];
echo "</td>";
echo "<td>";
echo $row['program'];
echo "</td>";
echo "<td>";
echo $row['entry_year'];
echo "</td>";
echo "<td>";
echo $row['study_group'];
echo "</td>";
echo "<td>";
echo $row['group_members'];
echo "</td>";
echo "<td>";
echo $row['group_leader'];
echo "</td>";
echo "</tr>";
echo "<br/>";
exit;
}else{
echo "0 results";
}
}
mysqli_close($conn);
?>

Related

How to make sql query to display 1 result based on id in the database table

I need help, I cannot figure out, I cannot find why I am having errors and I am not able to achieve something freaking simple.
Long story short, I have a website to manage projects, so when I run the search function it throws a table with some records from the database, there is a button called "see details" which is assigned to a project id with database i.e. 21, 1, 48 etc, the problem is that when I click "see details" it throws everything from the table proposals instead of 1 project, no matter which button I click on, if its id 1, 21, 48, it prints everything.
details page
details.php:
<?php
include '../includes/config.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM proposals_table WHERE id LIKE '_%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered'>";
echo "<tr>";
echo "<th>Organisation</th>";
echo "<th>Project</th>";
echo "<th>Proposal Date</th>";
echo "<th>Date Received</th>";
echo "<th>Notes</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['proposal_date'] . "</td>";
echo "<td>" . $row['date_received'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
search/result page
proposals.php
<?php
include '../includes/config.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM proposals_table";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered'>";
echo "<tr>";
echo "<th>Organisation</th>";
echo "<th>Project</th>";
echo "<th>Proposal Date</th>";
echo "<th>Date Received</th>";
echo "<th>Options</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['proposal_date'] . "</td>";
echo "<td>" . $row['date_received'] . "</td>";
echo "<td> <a class='btn btn-primary' href='details.php?id={$row['id']}'>See details</a></td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
If you want to show only the selected element on your details page then you need to fetch only that selected item from the database.
First of all you should separate HTML from PHP. The best would be to have them in separate files. In PHP you prepare the data to be displayed and then in HTML you fill in the blanks with PHP values.
To select a value from MySQL using a given ID you must use prepared statements with parameter binding. So if you create your link in this way:
echo "<td> <a class='btn btn-primary' href='details.php?id=".urlencode($row['id'])."'>See details</a></td>";
You can receive this ID in your details page using $_GET['id']. You can bind that value to your WHERE clause in SQL.
<?php
include '../includes/config.php';
// Attempt select query execution
$stmt = $link->prepare("SELECT * FROM proposals_table WHERE id=?");
$stmt->bind_param('s', $_GET['id']);
$stmt->execute();
$proposals = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if($proposals) {
?>
<table class='table table-bordered'>
<tr>
<th>Organisation</th>
<th>Project</th>
<th>Proposal Date</th>
<th>Date Received</th>
<th>Notes</th>
</tr>
<?php foreach($proposals as $row): ?>
<tr>
<td><?=$row['company'] ?></td>
<td><?=$row['project'] ?></td>
<td><?=$row['proposal_date'] ?></td>
<td><?=$row['date_received'] ?></td>
<td><?=$row['notes'] ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
} else {
echo 'No records matching your query were found.';
}
And of course your config.php page should look like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'user', 'pass', 'db');
$link->set_charset('utf8mb4'); // always set the charset

simple else with while in loop not working

My code is working as for my needs. But the only thing bugging me is
the "else" is not working. When i search for a correct record the
record will appear and it was running fine. But if i Incorrectly
search a record nothing will happen. i am expecting "Records not Found" will echo but nothing happen.
}else{
echo "Records not found";
}
This is the whole code.
<?php
$conn = mysqli_connect("localhost", "root", "", "my1stdb") or die("could not connect");
$set = $_POST['search'];
if ($set) {
$show = "SELECT * FROM users where email='$set'";
$result = mysqli_query($conn, $show);
while ($rows = mysqli_fetch_array($result)) {
echo "Registrant Found";
echo "<tr>";
echo "<td>";
echo $rows['username'];
echo "</td>";
echo "<td>";
echo $rows['fullname'];
echo "</td>";
echo "<td>";
echo $rows['password'];
echo "</td>";
echo "<td>";
echo $rows['email'];
echo "</td>";
echo "</tr>";
echo "<br/>";
}
} else {
echo "Records not found";
}
?>
</table>
You need to use mysqli_num_rows() along with mysqli_fetch_assoc():-
<?php
$conn=mysqli_connect("localhost","root","","my1stdb") or die("could not connect");
$set = $_POST['search'];
if($set) {
$show="SELECT * FROM users where email='$set'";
$result=mysqli_query($conn,$show) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){ // check data present or not
while($rows=mysqli_fetch_assoc($result)){ // for lighter array due to associative indexes only
echo "Registrant Found";
echo "<tr>";
echo "<td>";
echo $rows['username'];
echo "</td>";
echo "<td>";
echo $rows['fullname'];
echo "</td>";
echo "<td>";
echo $rows['password'];
echo "</td>";
echo "<td>";
echo $rows['email'];
echo "</td>";
echo "</tr>";
echo "<br/>";
}
}else{
echo "Records not found";
}
}else{
echo "Please insert search term";
}
?>
</table>
Note:- Your code is wide-open for SQL INJECTION. to prevent from it use prepared statements
Reference:-
mysqli prepared statements
PDO prepared statements
You could count the number of results returned.
if($set) {
$show="SELECT * FROM users where email='$set'";
$result=mysqli_query($conn,$show);
$recordCount = 0;
while($rows=mysqli_fetch_array($result)){
$recordCount++;
echo "Registrant Found";
echo "<tr>";
echo "<td>";
echo $rows['username'];
echo "</td>";
echo "<td>";
echo $rows['fullname'];
echo "</td>";
echo "<td>";
echo $rows['password'];
echo "</td>";
echo "<td>";
echo $rows['email'];
echo "</td>";
echo "</tr>";
echo "<br/>";
}
if($recordCount==0){
echo "Records not found";
}
}

Execute MySQL Delete on Button Click

In my code, I am showing a table within my database called staff in a HTML table and I want to add a delete button to each row in the HTML table that when clicked, it will delete the record its associated with.
Based on searching other solutions, my code looks like this:
staff.php:
require_once('../connection.php');
//delete row on button click
if(isset($_GET["del"])){
$idc = $_GET["del"];
if($VisitorManagement->query("DELETE FROM staff WHERE id=$idc")){
header('Location: delete-thankyou.php');
} else {
echo "Failed to delete staff member.";
}
}
$result = mysqli_query($VisitorManagement, "SELECT * FROM staff ORDER BY fullName");
echo "<table id='staff'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row['fullName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td><a class='button alert' href='staff.php?del=".$row["idc"]."'>Delete</a></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
connection.php:
$hostname_VisitorManagement = "localhost";
$database_VisitorManagement = "visitor-management";
$username_VisitorManagement = "***";
$password_VisitorManagement = "***";
$VisitorManagement = mysqli_connect($hostname_VisitorManagement, $username_VisitorManagement, $password_VisitorManagement, $database_VisitorManagement);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
date_default_timezone_set('America/New_York');
Unfortunately, when I go to the click one of the buttons, it fails to delete the record and echoes the error message pre-defined in staff.php. Am I missing something to get this to work?
I was able to fix it by changing all instances of idc to id.
New code is:
require_once('../connection.php');
//delete row on button click
if(isset($_GET["del"])){
$id = $_GET["del"];
if($VisitorManagement->query("DELETE FROM staff WHERE id=$id")){
header('Location: delete-thankyou.php');
} else {
echo "Failed to delete staff member.";
}
}
$result = mysqli_query($VisitorManagement, "SELECT * FROM staff ORDER BY fullName");
echo "<table id='staff'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row['fullName'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td><a class='button alert' href='staff.php?del=".$row["id"]."'>Delete</a></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";

How do i do a php search where the string can either be 5 or 6 characters?

I am building a zip/postal code search for the US & Canada. I have the code working great with just the US zip code search, which are 5 characters. The Canadian Postal codes are 6 characters. I need this code so if the user only adds 1-4 characters, if it matchs anything in the database, I don't want those results displayed, becuase it would display hundreds and they would all be wrong.
In my code, I have:
if (strlen($search_name)>=5)
How do I set this up so it takes both 5 or 6 characters?
So, this is the code I am using:
<?php
if (isset($_POST['search_name'])) {
$search_name = $_POST['search_name'];
if (!empty($search_name)) {
if (strlen($search_name)>=5) {
$query = "SELECT * FROM `search4` WHERE `ZipCode` LIKE '%".mysql_real_escape_string($search_name)."%'";
$query_run = mysql_query($query);
if (mysql_num_rows($query_run)>=1) {
echo "<table width=700' border='0'>";
echo "<tr>";
echo "<td width='700' valign='top'><table width='100%' border='0'>";
echo "<tr>";
echo "<td><p><strong>Results found: </strong></p>";
while ($query_row = mysql_fetch_assoc($query_run)) {{
echo $query_row ['ZipCode'].', ';
echo $query_row['ZipCity'].', ';
echo $query_row['ZipState'].'<br>';
echo '<p><strong>Area: </strong></p>'; echo $query_row['Area'].'';
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo '<span class="productdescription"><p>Mar Cor Office: </p></span></h2>';
echo $query_row['MCPOffice'].', ';
echo $query_row['CustClassID'].'<br>';
echo $query_row['Address1'].'<br>';
if(!empty($query_row['Address2'])) // This will skip if the field if it's empty
echo $query_row['Address2'].'<br>';
echo $query_row['City'].', ';
echo $query_row['State'].' ';
echo $query_row['Zip'].'<br>';
echo '<p><strong>Phone Number: </strong></p>';
echo $query_row['Phone'].'<br>';
echo '<p><strong>Fax Number: </strong></p>';
echo $query_row['Fax'].'<br><br>';
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
//BeginImage display result
$res=mysql_query("select * from Images");
{
echo "<td width='703' align='right' valign='top'>";?> <img src="<?php echo $query_row["Image"]; ?>"> <?php echo "</td>";
echo "</tr>";
}
//EndImage display result
}
}
}else{
echo 'No results found.';
}
}else{
echo 'Your search must be a 5-digit zip code.';
}
}
}
?>
if(strlen($search_name) == 5 || strlen($search_name) == 6) {
// Whatever your code is here
}
This condition will only pass if the string length is 5 characters or 6 characters
Strlen manual here

Set background color of cells based on MySQL query output

I am new to PHP and trying to learn enough to do some basic functions. I've been able to create a table for my users to edit themselves, and redisplay but I've come across a question.
Using the script below, users can input their skill level for various products. I wanted to be able to highlight each cell in which they input "0" or blank. User's input will be between 0-5 (or blank if they haven't filled it in yet).
This is all being done on my localhost so I'll admit all the security measures are not quite there.
I've read a lot of posts and tried to figure it out myself, but I'm doing something fundamentally wrong I believe.
Any assistance on this would be greatly appreciated. I've been known to buy a beer (via paypal) for those who help me with coding :)
Here is my existing code for printing out the results of the database:
<?php
//This will connect to the database in order to begin this page
mysql_connect("localhost", "root", "time2start") or die (mysql_error());
//Now we will select the database we need to talk to
mysql_select_db("joomla_dev_15") or die (mysql_error());
$query = "SELECT * FROM enterprise_storage WHERE id=1";
$result = mysql_query($query) or die (mysql_error());
echo "<table border='1'>";
echo "$row";
echo "<tr> <th>Product</th> <th>Wayne Beeg</th> <th>Paul Hamke</th> <th>Steve Jaczyk</th> <th>David Jontow</th> <th>Ed MacDonald</th> <th>Michael Munozcano</th> <th>Ron Shaffer</th> <th>Luke Soares</th> <th>Josh Wenger</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['model'];
echo "</td><td>";
echo $row['beeg'];
echo "</td><td>";
echo $row['hamke'];
echo "</td><td>";
echo $row['jaczyk'];
echo "</td><td>";
echo $row['jontow'];
echo "</td><td>";
echo $row['macdonald'];
echo "</td><td>";
echo $row['munozcano'];
echo "</td><td>";
echo $row['shaffer'];
echo "</td><td>";
echo $row['soares'];
echo "</td><td>";
echo $row['wenger'];
echo "</td></tr>";
}
echo "</table>";
?>
<FORM>
<INPUT TYPE="BUTTON" VALUE="Return to the Home Page" ONCLICK="window.location.href='http://localhost/~user/joomla15/custom/skilldisplay.php'">
</FORM>
Maybe
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr>";
foreach($row as $content) {
if($content == 0) {
echo "<td style='background-color:gray;'>";
}
else {
echo "<td style='background-color:green;'>";
}
echo $content . "</td>";
}
echo $row['wenger'];
echo "</td>";
}
echo "</tr></table>";
try something like this
add this to of your generated document
<style type="text/css">
.red{ background-color: red; }
</style>
This is your PHP:
<?php
// sanitize value
$value = trim($row['model']);
$class = (empty($value)) ? 'red' : '';
// display
echo "<td class=\"$class\">$value</td>";
...
?>
Ok, so I managed to get it working finally. The two replies above helped me figure out the right approach to doing this.
Of course, my approach may not be the best method, but I've tested it and it works for my needs. For any future searchers, here's what I did:
<?php
//This will connect to the database in order to begin this page
mysql_connect("localhost", "root", "time2start") or die (mysql_error());
//Now we will select the database we need to talk to
mysql_select_db("joomla_dev_15") or die (mysql_error());
$query = "SELECT * FROM enterprise_storage";
$result = mysql_query($query) or die (mysql_error());
echo "<table border='1'>";
echo "$row";
echo "<tr> <th>Product</th> <th>Wayne Beeg</th> <th>Paul Hamke</th> <th>Steve Jaczyk</th> <th>David Jontow</th> <th>Ed MacDonald</th> <th>Michael Munozcano</th> <th>Ron Shaffer</th> <th><a href='http://localhost/~user/joomla15/custom/updateform.php'>Luke Soares</a></th> <th>Josh Wenger</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['model'];
echo "</td>";
if ($row['beeg'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['beeg'] ;
}else{
echo '<td>' .$row['beeg'];
}
echo "</td>";
if ($row['hamke'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['hamke'] ;
}else{
echo '<td>' .$row['hamke'];
}
echo "</td>";
if ($row['jaczyk'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['jaczyk'] ;
}else{
echo '<td>' .$row['jaczyk'];
}
echo "</td>";
if ($row['jontow'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['jontow'] ;
}else{
echo '<td>' .$row['jontow'];
}
echo "</td>";
if ($row['macdonald'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['macdonald'] ;
}else{
echo '<td>' .$row['macdonald'];
}
echo "</td>";
if ($row['munozcano'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['munozcano'] ;
}else{
echo '<td>' .$row['munozcano'];
}
echo "</td>";
if ($row['shaffer'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['shaffer'] ;
}else{
echo '<td>' .$row['shaffer'];
}
echo "</td>";
if ($row['soares'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['soares'] ;
}else{
echo '<td>' .$row['soares'];
}
echo "</td>";
if ($row['wenger'] == '0'){
echo '<td bgcolor="#FF0000">' . $row['wenger'] ;
}else{
echo '<td>' .$row['wenger'];
}
echo "</td></tr>";
}
echo "";
?>

Categories