PHP: search from mysqli - php

I have a search.php page with this code
<html>
<body style="background-color: azure">
please import your search request:
<br>
<form method="get" action="searchprocess.php">
<input type="text" placeholder="please import here" name="search">
<input type="submit">
</form>
</body>
</html>
and the searchprocess.php is below
<?php
require_once 'functions.php';
$search=$_GET['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query="Select * from names where firstname LIKE '%$search%'";
$result=mysqli_query($connection,$query);
$count =mysqli_num_rows($result);
var_dump($result);
if ( $count == 0)
{
$output = "there is noting to show you ... sorry search another thing <a href='search.php'>back to search page</a>";
echo $output;
}
else{
echo "<table>";
while($row = mysqli_fetch_array($result)){
$id = $result['id'];
$firstname = $result['firstname'];
$lastname = $result['lastname'];
echo '<tr>';
echo '<td>'.$id.'</td>';
echo '<td>'.$firstname.'</td>';
echo '<td>'.$lastname.'</td>';
echo '</tr>';
}
echo "</table>";
}
?>
I have wamp and problem is when try my code it's error on line on the line below
$id=$row['id'];

Youuse the wrong var.
while($row = mysqli_fetch_array($result)){
$id = $result['id'];
$firstname = $result['firstname'];
$lastname = $result['lastname'];
Should be:
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
I encourage you to use prepared statements to avoid SQL injection attacks.

Related

How to insert a search result into a table using php?

This is the code that I've got to search and it just appears next to each other. Can I put html within php and how would this be done? Or should I make a table below the form?
<?php
include ('database_conn.php');
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM attendance WHERE stud_id LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$stud_id = $row ['stud_id'];
$module = $row ['module'];
$attendance_status = $row ['attendance_status'];
$output .='<div> '.$stud_id.''.$module.''.$attendance_status.'</div>';
}
}
}
?>
This is the form that I've got in the HTML to search
<form action ="CM0671_attendance.php" method = "post">
<input name="search" type="text" size="30" placeholder="Student ID"/>
<input class="btn btn-primary" type="submit" value="Search"/>
</form>
Replace your while with this:
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Module</th>";
echo "<th>Status</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($query)) {
$stud_id = $row ['stud_id'];
$module = $row ['module'];
$attendance_status = $row ['attendance_status'];
echo "<tr>";
echo "<td>{$stud_id}</td>";
echo "<td>{$module}</td>";
echo "<td>{$attendance_status}</td>";
echo "</tr>";
}
echo "</table><br>";

How do I create an edit-option for each row in a table?

I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.

Session variable and Dynamic Pagination in php

<form action='movies.php' method='POST'>
Language: <select name="language">
<option selected>hindi</option>
<?php
require("config.php");
$result="SELECT language FROM movies";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q)) {
$s1=$row["language"];
echo "<option>
$s1
</option>";
}
echo "<br>"
?>
</select>
<br /> <br />
<input type='submit' value='Submit' />
</form>
<?php
$lang=#$_POST['language'];
$_SESSION["lang1"]=$lang;
/*
if($lang){
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="query"> <img src="images\tiles\bb.jpg"> ';
echo "<h3> " . $row["name"]."</h3>". "<br>";
echo "</div>";
}
} else {
echo "0 results";
}
}
*/
$page=#$_GET['page'];
if($page==""|| $page=="1")
{
$page1=0;
}
else{
$page1=($page*3)-3;
}
$sql = "SELECT name,language FROM movies WHERE language='". $_SESSION['lang1']."' limit $page1,3 ";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
while ($list=mysqli_fetch_array($result))
{
echo $list['name'] . " : " . $list['language'] . "<br />";
}
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
$numrows=$a;
$rowsperpage=3;
$totalpages= ceil($numrows/$rowsperpage);
echo "</br>";
for($b=1;$b<=$totalpages;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
I get proper output on movies.php which is the first 3 rows from database,but when i click on the dynamically created pagination link like movies.php?page=2 then there is no output on this page.This code works fine if i manually set the
$_SESSION["lang1"]="English"; then i get proper output but when i take input from the form it doesnt work.

Multiple search form using functions and if else

Hi Im creating a multiple search form using PHP,HTML,SQL with the use of functions, for example I have 3 search fields Firstname, lastname and email. I would let the user input from any of those, therefore i would be needing the if else statement, but to be able to satisfy all conditions it would take a lot of if else, so i think of using a function to output the table and place it inside the if else after the query on the database. But it seems that it could not be able to search in the database if I do it like this it outputs "0 results", but if i remove the function and place it on the end of my script I am able to search in the db but it could not detect my else condition which is "You have not yet entered any values"
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if (!empty($sfname) && empty($slname) && empty($semail) )
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%'" ;
checkres();
}
else if (!empty($sfname) && !empty($slname) && empty($semail))
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
checkres();
}
else
{
echo "You have not yet entered any values ";
}
mysqli_close($conn);
?>
This is the new one
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$sfname = $_POST["fname"];
$slname = $_POST["lname"];
$semail = $_POST["email"];
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
You have a few errors:
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
You have %slname instead of $slname.
Another mistake is in the program flow. Your else condition, which is saying :"You have not yet entered any values" will be reached in two cases:
When all fields are left blank
When all fields are filled with values.
You don't want that. You have to improve your logic, and build a query based on that, and that can be done like this:
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '$semail'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
What you do is in my opinion a little bit confusing (and a little bit odd n terms of the program's flow structure).
You can simply use an array of variables for your input fields and then loop through the array to generate your SQL statement. So your HTML form would look like this:
<form method="post" action="#" id="searchform">
First Name:<br />
<input type="text" name="queryArray[FirstName]" />
<br />Last Name:<br />
<input type="text" name="queryArray[LastName]" />
<br />Email:<br />
<input type="text" name="queryArray[Email]" />
<br />
<input type="submit" name="submit" value="Search" />
</form>
A more clear structure would be if you define these 2 functions, which of course can be placed anywhere in your PHP code block:
function createSql($queryArray) {
if (is_array($queryArray)) {
$sql = null;
foreach ($queryArray as $key => $value) {
if ($value != null ) {
$addQuery = "`".$key."` LIKE '%".$value."%'";
if ($sql == null)
$sql = "SELECT * FROM `Userlist` WHERE ".$addQuery;
else
$sql = $sql." AND ".$addQuery;
}
return $sql;
}
}
function checkres($sql) {
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0) {
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else
echo "0 results";
// Close connection
mysqli_close($conn);
}
Finally you will have to call the functions according to user activity:
if ($_POST != null) {
$sql = createSql($_POST[queryArray]);
checkres($sql);
}
An example how the SQL generation works is listed here

create a Compare page using checkbox and data from mysql

Im a newbie in PHP and I want to create a simple webpage app for my website, I was able to produce this page base on a tutorial here.
<?php
$con = mysql_connect("localhost","*****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*****", $con);
$result = mysql_query("SELECT * FROM products");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>classification</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['classification'] . "</td>";
echo "<td><input type='checkbox' name='{number[]}' value='{$row['prodID']}' /></td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
<?php
?>
<html>
<head>
</head>
<form name="form1" method="post" action="result_page.php">
<input type="submit" name="Submit" value="Submit">
</p>
</form>
<body>
</body>
</html>
but my problem is how to create a result_page.php to show the selected entries or data base on the selected checkbox so i can create a comparison page. I have this as being my result_page.php but nothing is showing up. I know Im doing something wrong but I cant find out.
<?php
error_reporting(E_ALL);
$host = 'localhost';
$user = '******';
$pass = '******';
$dbname = '******';
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
mysql_select_db($dbname);
$sql = "SELECT * FROM products WHERE prodID IN (";
foreach ($_POST['number'] as $product) $sql .= "'" . $product . "',";
$sql = substr($sql,0,-1) . ")";
$result = mysql_query($sql);
while ($myrow = mysql_fetch_array($result))
{
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
}
?>
A quick glance, the section that generates the output is not correct. You have looped two times for no apperant reason.
while ($myrow = mysql_fetch_array($result)) //<========remove this line
{ //<========remove this line
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
} //<========remove this line
This is done by human parse, but should serves as a starting point.
And to recap tadman, no this is not a good tutorial. And normally you won't need to do printf for the output.

Categories