search page not displaying any results - php

please assist
I have created a search page to query the database, when the submit button is selected, no data is populated into the grid and there is no error message or notice that gives me an indication of where the issue is. Please assist.
Here is the code:
<?php
if(isset($_POST['submit']))
{
$txtLastName = $_POST['txtLastName'];
$txtidnumber = $_POST['txtidnumber'];
$txtMedicalAidNumber = $_POST['txtMedicalAidNumber'];
//connect to the database
$db = mysql_connect
("server", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$mydb = mysql_select_db("mediouqp_login");
if($txtLastName != '' && $txtidnumber != '' && $txtMedicalAidNumber != '')
{
$sql = "SELECT last_name, id_number, medical_id_number FROM patient WHERE last_name LIKE '%" . $txtLastName . "%' OR id_number LIKE '%" . $txtidnumber ."%'";
}
else
{
$sql = "SELECT last_name FROM patient ORDER BY last_name DESC";
}
$result = mysql_query($sql);
}
if($result)
{
if(mysql_num_rows($result) > 0)
{
echo 'Total records found are- '.mysql_num_rows($result);
}
else
{
echo "No records found.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
<body>
<ul>
<li>PATIENT DETAILS
<li>REPORTS</li>
<li>ADMINISTRATOR</li>
<li>DOWNLOADS</li>
</ul>
<div class="headerTitle">
<h1 id="mainHeader">search patient details</h1>
</div>
<form action="search_patient.php" method="post" name="frm_search" id="frm_search">
<table>
<tr>
<td class="Label" id="lname">Last Name
</td>
<td class="Field">
<input type ="lastname" name ="txtLastName" ></input>
<span id="spnLastName"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">ID Number
</td>
<td class="Field">
<input type ="lastname" name ="txtidnumber" ></input>
<span id="spnIdNumber"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">Medical Aid Number
</td>
<td class="Field">
<input type ="medicalaidnumber" name ="txtMedicalAidNumber" ></input>
<span id="spnMedicalaidNumber"></span>
</td>
</tr>
<tr>
<td class="Label">
</td>
<td>
<input type="submit" id="btnSearchPatient" value="Submit"></input>
<input type = "button" onClick="window.location='create_patient.php';" value="Create Patient" /></input>
</td>
</tr>
</table>
</form>
<br/>
<br/>
<table id="tblpatient" class="Grid">
<tr class="Header">
<td> </td>
<td> </td>
<td> </td>
<td>Last Name</td>
<td>ID Number</td>
<td>Medical Aid</td>
</tr>
<?php
if($result)
{
while($row = mysql_fetch_array($result))
{
$last_name = $row['last_name'];
$id_number = $row['id_number'];
$medical_id_number = 0;//$row['medical_id_number'];
?>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><?php echo $last_name;?></td>
<td><?php echo $id_number;?></td>
<td><?php echo $medical_id_number;?></td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>

Note: This extension(mysql) 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 along with prepared statements.
As per the code you have written it will be submitting the data but what you have written under this statement will never Work.
if(isset($_POST['submit'])){// Codes Inside this}
Reason this code will not work
Your Submit button is not having the name which you have given in the isset($_POST['submit']).
You mist add the name to the submit button which you have in your code.
Replace your Submit button as i have provided by adding the name to it and changing the button code style.
Replace:
<input type="submit" id="btnSearchPatient" value="Submit"></input>
With:
<input type="submit" id="btnSearchPatient" name="submit" value="Submit" />
After all the above steps that has been provided ensure the note below in order the data comes as not expected.
Note: If you need to execute the statement perfect you first put echo to the select statement that you have coded and break the execution over there. You will find the SQL statement over to the browser and you copy that echoed statement into the SQL section of the DB created in the Phpmyadmin and check whether your code executed well. If so you got the required output that you can remove the echo and exit statement and you can proceed.

Related

MySQL table page not loading correct data

I'm creating a table that uses PHP to pull from a MySQL database that I have. I think I've got everything where I want it to be, however the only problem I'm having is that the results seem to be (for lack of a better word) "behind". What I mean by that is that my first page index.php is where I'm accepting user edits to the database. Once they click Update it sends them to my results.php file that is supposed to actually perform the SQL UPDATE and then display the updated table.
It updates the table just fine according to XAMPP's database editor. However, when I said "behind" I mean that the page loads, updates but doesn't display the updated data until either the user refreshes the page or returns to the first page THEN comes back. I'm not sure what could be causing it, so I'm hoping someone here can help me. I feel like the reason is something as simple as I'm just running the code in the wrong order, but I don't know for sure. My code is below:
index.php
<html>
<body>
<?php
include('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
?>
<form name="form1" method="post" action="results.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<input name="event_id[]" type="hidden" id="event_id" value="<?php echo $rows['event_id']; ?>">
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<input name="title[]" type="text" id="title">
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<input name="date[]" type="date" id="date">
</td>
<td align="center">
<input title="Use reference tables below to enter speaker ID" name="speaker[]" type="text" id="speaker">
</td>
<td align="center">
<input title="Use reference tables below to enter building ID" name="building[]" type="text" id="building">
</td>
<td align="center">
<input title="Use reference tables below to enter Room ID" name="room[]" type="text" id="room">
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Update" value="UPDATE"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<html>
<body>
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
?>
<form name="form1" method="post" action="index.php">
<table width="auto" border="1" cellspacing="1" cellpadding="5">
<tr>
<td align="center"><strong>Event ID</strong></td>
<td align="center"><strong>Title</strong></td>
<td align="center"><strong>Topic</strong></td>
<td align="center"><strong>Description</strong></td>
<td align="center"><strong>Event Date</strong></td>
<td align="center"><strong>Speaker</strong></td>
<td align="center"><strong>Building</strong></td>
<td align="center"><strong>Room</strong></td>
</tr>
<?php
while($rows=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center">
<?php echo $rows['event_id'];?>
</td>
<td align="center">
<?php echo $rows['title']; ?>
</td>
<td align="center">
<?php echo $rows['topic_name']; ?>
</td>
<td align="center">
<?php echo $rows['topic_description']; ?>
</td>
<td align="center">
<?php echo $rows['event_date']; ?>
</td>
<td align="center">
<?php echo $rows['speaker_name']; ?>
</td>
<td align="center">
<?php echo $rows['building_name']; ?>
</td>
<td align="center">
<?php echo $rows['room_name']; ?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="8" align="center"><input type="submit" name="Return" value="Return"></td>
</tr>
</table>
</form>
</body>
</html>
Also if someone can give me some guidance as to how to run the htmlspecialchars function on my arrays within results.php I'd really appreciate it. I've already tried to create a for loop for literally each array but that didn't work. I've tried using ->
<?php
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
but that also didn't work, and I've tried using the array_walk_recursive but to no avail. I want to try and do something like W3Schools' example here W3Schools Form Validation towards the bottom of the page where it says Validate Form Data With PHP and then gives an example.
The result you get from the UPDATE query is the number of affected rows in your database. To correctly display the updated data, you need to re-fetch from the database before you generate the HTML. You should rearrange your code in results.php like this:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);
require_once('dbconnect.php');
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['event_id'];
$title2 = $_POST['title'];
$date2 = $_POST['date'];
$speaker2 = $_POST['speaker'];
$building2 = $_POST['building'];
$room2 = $_POST['room'];
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++) {
$sql="UPDATE events SET title='$title2[$i]', event_date='$date2[$i]', speaker='$speaker2[$i]', building='$building2[$i]', room='$room2[$i]' WHERE event_id='$id[$i]'";
$result1=mysqli_query($conn, $sql);
}
}
$query = "SELECT * FROM vw_events";
$result = mysqli_query($conn, $query);
Side note: If your data is sensitive, you may want to read about mysqli prepared statement so hackers cannot tamper with your queries.
Regarding your question about htmlspecialchars, see Stackoverflow "Execute htmlspecialchars on a multi level array".

how do fetching and then inserting from multi check boxes in php

I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.

How can i insert html table data into sql database using php?

This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]
To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.

add a new set of data and store into database

cannot find out what is the problem...for example i want to add 2 row of data...when i press the + button...my data just typed will gone(looks like refresh)...and database will only store the 2nd row of data...1st one will not store. please help me find out the answer. thank you~
<?php if($_POST['btnPlus1'])
$_SESSION['count1'] += 1;
else if($_POST['btnMinus1'])
$_SESSION['count1'] -= 1;
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES('".$_POST['txtStaffIc']."','".strtoupper($_POST['txtUniversity'])."','".strtoupper($_POST['sLevel'])."','".strtoupper($_POST['txtSpecialization'])."','".$_POST['txtYear']."')";
$AddEducationalResult = mysql_query($AddEducationalQ,$link); ?>
<tr>
<td>
<fieldset>
<legend>Educational Background</legend>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<?php
for($tempfield = 1; $tempfield <= $_SESSION['count1']; ++$tempfield)
{?>
<fieldset>
<legend><?php echo $tempfield ?></legend>
<table width="200" border="0">
<tr>
<td>University</td>
<td>Level</td>
<td>Specialization</td>
<td>Year Graduated</td>
</tr>
<tr>
<td>
<input type="text" name="txtUniversity" id="txtUniversity" /></td>
<td>
<select name="sLevel" id="sLevel">
<option></option>
<option>Diploma</option>
<option>Degree</option>
<option>Master</option>
<option>Doctor</option>
</select>
</td>
<td>
<input type="text" name="txtSpecialization" id="txtSpecialization" />
</td>
<td>
<input type="text" name="txtYear" id="txtYear" />
</td>
</tr>
</table>
</fieldset>
<?php
}?>
</td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" name="btnPlus1" id="btnPlus1" value="+" /> <input type="submit" name="btnMinus1" id="btnMinus1" value="-" /></td>
</tr>
</table>
</fieldset>
</td>
</tr>
Ok first you'll have to change your form element to:
<form method="post" action="filename.php" accept-charset="utf-8">
Make sure you change filename.php to the filename of this code.
Now you'll have to make a choice. You can either continue with mysql_*, which is deprecated and extremely insecure! Or you can upgrade your code to PDO() instead.
If you wish to continue with mysql_*, change your PHP part to:
if(isset($_POST['txtStaffIc'], $_POST['txtUniversity'], $_POST['sLevel'], $_POST['txtSpecialization'], $_POST['txtYear'])){
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES('".$_POST['txtStaffIc']."','".strtoupper($_POST['txtUniversity'])."','".strtoupper($_POST['sLevel'])."','".strtoupper($_POST['txtSpecialization'])."','".$_POST['txtYear']."')";
mysql_query($AddEducationalQ,$link) or die(mysql_error());
echo "Data succesfully added to database.";
}
If you wish to upgrade to PDO() instead, change your PHP part to:
if(isset($_POST['txtStaffIc'], $_POST['txtUniversity'], $_POST['sLevel'], $_POST['txtSpecialization'], $_POST['txtYear'])){
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES(':txtStaffIc',':txtUniversity',':sLevel',':txtSpecialization',':txtYear')";
$prepare = $pdo->prepare($AddEducationalQ);
$prepare->bindValue(":txtStaffIc",$_POST['txtStaffIc']);
$prepare->bindValue(":txtUniversity",strtoupper($_POST['txtUniversity']));
$prepare->bindValue(":sLevel",strtoupper($_POST['sLevel']));
$prepare->bindValue(":txtSpecialization",strtoupper($_POST['txtSpecialization']));
$prepare->bindValue(":txtYear",$_POST['txtYear']);
if($prepare->execute()){
echo "Data succesfully added to database.";
} else {
print_r($prepare->errorInfo());
}
}
Also make sure you change your database connection file to:
<?php
$dbhost = ""; //Enter MySQL server host
$dbuser = ""; //Enter MySQL database user
$dbpass = ""; //Enter MySQL database pass
$dbname = ""; //Enter MySQL database name
$pdo = new PDO("mysql:host=".$dbhost.";dbname=". $dbname, $dbuser, $dbpass);
?>
On a last note I should add that I didn't see any require database connection file inside your PHP code. I assume you simply didn't post this.

PHP Post Variable Problem

It's been a little while with PHP, so please excuse my ignorance. I have this web page:
<?php
mysql_connect ("localhost", "user", "pass");
mysql_select_db ("expiration");
if (isset ($_REQUEST['new_expire']) && $_REQUEST['new_expire'] != "") {
$insert_query = "INSERT INTO files (path, expires) VALUES ('";
$insert_query .= $_REQUEST['new_path'];
$insert_query .= "', '";
$insert_query .= $_REQUEST['new_expire'];
$insert_query .= "');";
mysql_query ($insert_query);
}
?>
<html>
<head></head>
<body>
<?php echo print_r $_REQUEST; ?>
<form action="index.php" method="POST">
<p>Add New Expiration</p>
<table>
<tr>
<td align="right">
Select File:
</td>
<td>
<select id="new_path">
<?php $options = buildOptions (); echo $options; ?>
</select>
</td>
</tr>
<tr>
<td align="right">
MySQL Expire Time:
</td>
<td>
<input type="text" id="new_expire" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
mysql_close ();
?>
When I load the page, the result of the print_r is an empty array. When I submit the form, it's still empty. I get no new record in the database. Any ideas?
Change all the places you have id to name, for example:
<input type="text" id="new_expire" /> --> <input type="text" name="new_expire" />
The _REQUEST (either _POST or _GET) is only from input elements with a name

Categories