How do I display correct data from mySQL? - php

I am trying to query a database and display the results. The query is based on information from an html form. However, when I enter a name such as john in the form, for which the table has 2 entries with that name, I get 0 results. I don't know what the problem is.
Here is the html form:
<form action="cust_details_search.php" method="post">
Name :
<input type="text" name="name_search" id="name_search" >
Email :
<input type="email" name="email_search" id ="email_search" >
Phone no. :
<input type="phone" name="phone_search" id="phone_search" >
Address :
<input type="text" name="address_search" id="address_search" >
City :
<input type="text" name="city_search" id="city_search" >
State :
<input type="text" name="state_search" id="state_search" >
<br> <br>
Country :
<input type="text" name="country_search" id="country_search">
Product Enquired for :
<input type="text" name="prod_search" id="prod_search">
<input type="submit" value="Submit">
</form>
And the php file:
<?php
$server = "127.0.0.1";
$dbUsername = "root";
$dbPassword = "";
//create connection
$dbconn = new mysqli($server, $dbUsername, $dbPassword, $dbname);
$name_search = $_POST['name_search'];
$email_search = $_POST['email_search'];
$phone_search = $_POST['phone_search'];
$address_search = $_POST['address_search'];
$city_search = $_POST['city_search'];
$state_search = $_POST['state_search'];
$country_search = $_POST['country_search'];
$prod_search = $_POST['prod_search'];
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%.$name_search.%')
OR (`Phone no.` LIKE '%.$phone_search.%')
OR (`Address` LIKE '%.$address_search.%')
OR (`City` LIKE '%.$city_search.%')
OR (`State` LIKE '%.$state_search.%')
OR (`Country` LIKE '%.$country_search.%')
OR (`Product Enq. For` LIKE '%.$prod_search.%')
OR (`Email` LIKE '%.$email_search.%')");
?>
<html>
<head>
<title>Search Resutls</title>
<style>
body {
background-color: rgb(131,41,54);
}
h1 { color:#FFFFFF
}
h2 { color:#FFFFFF
}
p { color:#FFFFFF
}
</style>
</head>
<body>
<center>
<h2> Customer Details </h2>
<table style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone no. </th>
<th>Address </th>
<th>City </th>
<th>State </th>
<th>Country</th>
<th>Product Enquired for </th>
<th>Follow up details </th>
</tr>
</thead>
<tbody>
<?php
while($result = mysqli_fetch_assoc($run_query)) {
?>
<tr>
<td><?php echo $result['Name'] ?> </td>
<td><?php echo $result['Email'] ?></td>
<td><?php echo $result['Phone no.'] ?></td>
<td><?php echo $result['Address'] ?></td>
<td><?php echo $result['City'] ?></td>
<td><?php echo $result['State'] ?></td>
<td><?php echo $result['Country'] ?></td>
<td><?php echo $result['Product Enq. For'] ?></td>
<td><?php echo $result['Follow Up'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</center>
</body>
</html>
Any help is appreciated. Thank you in advance!

You are using the PHP concatenator . but you dont need to in a double quoted string. $variables are automatically expanded in a double quoted string so try
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%$name_search%')
OR (`Phone no` LIKE '%$phone_search%')
OR (`Address` LIKE '%$address_search%')
OR (`City` LIKE '%$city_search%')
OR (`State` LIKE '%$state_search%')
OR (`Country` LIKE '%$country_search%')
OR (`Product Enq For` LIKE '%$prod_search%')
OR (`Email` LIKE '%$email_search%')");
ALso some of your column names had a . in them? I assume these column names do not actually contain dots. However if the do, I suggest you remove them by editing your schema.
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's

Related

Php/SQL Table Search with Space

I setup a php file to pull data from a database, and list that on a table. I then made a simple search function to search that data, however I can't figure out how to implement a space when searching. For example, if I searched test 2 (test from one column, 2 from another) it won't display anything. However, if I were to search 'test2' or '2test' it displays all results. How would I implement that space into my code?
Here's my code:
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `master` WHERE CONCAT_WS(`id`, `office`, `firstName`, `lastName`, `type`, `status`, `deadline`, `contactPref`, `email`, `phoneNumber`, `taxPro`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `master`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "", "", "");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
echo "test";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="Untitled-1.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>ID</th>
<th>Office</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
<th>Status</th>
<th>Deadline</th>
<th>Contact Preference</th>
<th>Email</th>
<th>Phone Number</th>
<th>Tax Pro</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['office'];?></td>
<td><?php echo $row['firstName'];?></td>
<td><?php echo $row['lastName'];?></td>
<td><?php echo $row['type'];?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['deadline'];?></td>
<td><?php echo $row['contactPref'];?></td>
<td><?php echo $row['email'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
<td><?php echo $row['taxPro'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>```
A way to do this could be to have your string spillted up into words in php. You could use explode function for this (https://www.php.net/manual/en/function.explode.php)
And then write SQL where clause like this (im assuming you are using mysql):
WHERE col LIKE %word% OR col LIKE %word2%
This would be a bit inefficient, maybe the tool what you are looking for is elasticsearch? https://www.elastic.co/what-is/elasticsearch
Also, you should NEVER use . operator on an untrusted input. Because it creates MySQL Injection vulnerability. See this question for reference: How can I prevent SQL injection in PHP?
The simplest solution would be using FULLTEXT index in your mysql field. But I don't recommend using it on production. Instead, for actual projects external searching engine must be considered (e.g. Elasticsearch, etc.)

Delete row data from one table using check box and insert the deleted row data in another table

/*I have two table , 1st table name is bazar and 2nd table name is bazarduepayment having same columne name : sl,date,item,paid,due,remark. 'sl' is auto increment . Delete function is working perfectly . Someone please help me how to insert deleted row data in 2nd table 'bazarduepayment' Here below is code detail i wrote */
<?php
session_start();
include_once("rwdbconnection.php");
error_reporting(0);
if(isset($_POST['save']))
{
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++)
{
$del_id = $checkbox[$i];
mysqli_query($conn,"DELETE FROM bazar WHERE sl='".$del_id."'");
$message = "Data deleted successfully !";
}
}
$result = mysqli_query($conn,"SELECT * FROM bazar");
?>
<!DOCTYPE html>
<html>
<head>
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Delete data</title>
</head>
<body>
<div>
<?php if(isset($message)) { echo $message; } ?>
</div>
<form method="post" action="">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="checkAl"> Select All</th>
<th>Sl</th>
<th>Date</th>
<th>Item</th>
<th>Paid</th>
<th>Due</th>
<th>Remark</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="checkbox" id="checkItem" name="check[]" value="<?php echo $row["sl"]; ?>"></td>
<td><?php echo $row["sl"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["item"]; ?></td>
<td><?php echo $row["paid"]; ?></td>
<td><?php echo $row["due"]; ?></td>
<td><?php echo $row["remark"]; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
<p align="center"><button type="submit" class="btn btn-success" name="save">DELETE</button></p>
</form>
<script>
$("#checkAl").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
</script>
</body>
</html>
First you need to copy the data from one table to another using INSERT ... SELECT syntax and only then you can delete.
You should be using prepared statements for this.
if (isset($_POST['save'])) {
// Prepared INSERT query
$stmt_insert = $conn->prepare('INSERT INTO bazarduepayment(date,item,paid,due,remark)
SELECT date,item,paid,due,remark FROM bazar WHERE sl=?');
// Prepare DELETE query
$stmt_delete = $conn->prepare('DELETE FROM bazar WHERE sl=?');
// Loop on all checkboxes selected
foreach ($_POST['check'] as $del_id) {
$stmt_insert->bind_param('s', $del_id);
$stmt_insert->execute();
$stmt_delete->bind_param('s', $del_id);
$stmt_delete->execute();
}
}
You could even simplify this to get rid of the foreach loop entirely.

PHP search results not displaying from MySQL

After submitting the search the results returns a blank result set, nothing returns. Expecting it to return results from mysql search. Was working at one point but I am not sure what I changed to make it stop working.
Site is https://searchsoftball.com/search
I have verified the queries work with MySQL. No connection errors.
<?php
$localhost = "localhost";
$username = "";
$password = "";
$dbname = "seargobh_c";
$con = new mysqli($localhost, $username, $password, $dbname);
if( $con->connect_error){
die('Error: ' . $con->connect_error);
}
if( isset($_GET['search']) ){
$name = mysqli_real_escape_string($con, htmlspecialchars($_GET['search']));
$sql = "SELECT College.School, City, State, Conference, Division, Main, Softball, Camp FROM College
inner join Links on Links.School = College.School
WHERE College.school like '%$name%' or City like '%$name%' or Conference like '%$name%'
or Division like '%$name%' or State like '%$name%' or Team like '%$name%' order by Division, School desc";
}
$result = $con->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Form</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<label>Search</label>
<form action="search2a.php" method="GET">
<input type="text" placeholder="" name="search">
<input type="submit" value="Search Softball" name="btn" class="btn btn-sm btn-primary">
</form>
<h2>Search any of the below</h2>
<p> Until the search is more robust use these tips:<br>
Use the full state name<br>
For division, type out Division 1, etc.<br>
Searching for California will show schools, state, conference.</p>
<table class="table table-striped table-responsive">
<tr>
<th>School</th>
<th>City</th>
<th>State</th>
<th>Conference</th>
<th>Division</th>
<th>Main</th>
<th>Softball</th>
<th>Camp</th>
</tr>
<?php
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?php echo $row['School']; ?></td>
<td><?php echo $row['City']; ?></td>
<td><?php echo $row['State']; ?></td>
<td><?php echo $row['Conference']; ?></td>
<td><?php echo $row['Division']; ?></td>
<td><?php echo 'Main'; ?></td>
<td><?php echo 'Softball'; ?></td>
<td><?php echo 'Softball'; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
Results are based on criteria entered in search box. ie. California

retrieving information from two tables

I have a table called incidents, that i'd like to retrieve 4 fields/columns from, but i need firstname and lastname from the customer table. I keep getting the following error:
Warning: Invalid argument supplied for foreach()
This is the relevant code:
public static function get_incidents_unassigned(){
$db = Database::getDB();
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name, incident.productCode, incident.dateOpened, incident.title, incident.description FROM incidents
INNER JOIN customers
ON incident.customerID = customer.customerID
WHERE techID IS NULL';
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetch();
$incidentList = array();
foreach ($rows as $row){
$incidents = new Incident(
$row['name'], $row['productCode'],
$row['dateOpened'], $row['title'], $row['description']);
$incidentList[] = $incident;
}
$statement->closeCursor();
return $incidentList;
}
******but this is the involved table
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Date Opened</th>
<th>Title</th>
<th>Description</th>
<th> </th>
</tr>
<?php foreach ($incidents as $incident) :
$ts = strtotime($incident->getDate_Opened());
$date_opened_formatted = date('n/j/Y', $ts);
?>
<tr>
<td><?php echo htmlspecialchars($customer->getFullName()); ?></td>
<td><?php echo htmlspecialchars($incident->getProduct_Code()); ?></td>
<td><?php echo htmlspecialchars($incident->getTitle()); ?></td>
<td><?php echo htmlspecialchars($incident->getDescription()); ?></td>
<td><?php echo $date_opened_formatted; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="select_incident">
<input type="hidden" name="product_code"
value="<?php echo htmlspecialchars($incident->getIncident_id()); ?>">
<input type="submit" value="Select">
</form></td>
</tr>
<?php endforeach; ?>
</table>
//****may have been looking at too long!
You should add some error handling to your code. The db could tell you that incident is not defined. The data is selected from incidents but incident is used to identify the fields.
I mean try changing your statement to match your circumstances
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name,
inc.productCode, inc.dateOpened, inc.title,
inc.description FROM incidents inc
INNER JOIN customers
ON inc.customerID = customer.customerID
WHERE techID IS NULL';
Your database is able to give you error messages. These error messages describe what is your problem with your statement

HTML Table with inline PHP

I want to create a HTML Table, but the rows should be generated from the values from a mysql database. The problem is that I want to have a boolean box where the user can mark it, and then press a button to update the table in the database. How do I do such a thing ?
Code so far:
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$row = mysqli_num_rows($view_event_query);
$print = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border = '1'>
<tr>
<?php
while($row != 0){
echo "<td>".$print['hours']."</td>";
echo "<td>".$print['date']."</td>";
}
?>
</tr>
</table>
<form/>
</form>
</body>
</html>
You can easily iterate over the result from the mysqli_fetch_array function to create the table rows. Creating a checkbox markup is done easily, i assume that the table has a primary key id and the column, that stores the checkbox value (0 or 1) is called checkbox.
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$num_rows = mysqli_num_rows($view_event_query);
$rows = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border="1">
<thead>
<tr>
<td>Id</td>
<td>Date</td>
<td>Hours</td>
<td>Checkbox</td>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($num_rows); $i++) {
?>
<tr>
<td><?php print $rows[$i]["eid"]; ?></td>
<td><?php print $rows[$i]["date"]; ?></td>
<td><?php print $rows[$i]["hours"]; ?></td>
<td><input type="checkbox" name="row[<?php $rows[$i]["eid"]?>][checkbox]" value="1" <?php if ($rows[$i]["accepted"]) print ' checked="checked"'; ?>/></td>
</tr>
<?php
}
?>
</tbody>
</table>
<input type="submit" />
</form>
</body>
</html>

Categories