How to pass value in php - php

In my home page, I have a search bar with a button at the top of my page and I displayed all my songs using their title from my database underneath that.
The search bar is working fine since every song title I typed, it took me to the correct detail page.
I'm just wondering how can I also click on the song title and take me to each song detail page.
Home page
<?php
require_once '../config.php';
$sql = 'SELECT title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
//Search bar
<form action="chord/details.php" method="post" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
// Here I display all my songs from the database using their title
<?php
foreach ($songTitle as $song) {
// I'm not sure how to modify here.
echo "<a href='chord/details.php'>{$song['title']} <br> </a>";
} ?>
Details page
//This is working fine with Search Bar
<?php
require_once '../config.php';
if (isset($_POST['submit'])) {
$title = $_POST['search'];
$sql = 'SELECT * FROM song WHERE title = :title';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>

You can use the get HTTP method to send the id of the song to the details.php page and query to the database on that id.
And it's always a good practice to use the GET HTTP method for searching actions. As mickmackusa said in the comment:
$_POST is most appropriate when "writing" data server-side. $_GET is
most appropriate when "reading" data server-side.
So change the code on the Home page as below:
<?php
require_once '../config.php';
// query changed to fetch id as well
$sql = 'SELECT id , title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!-- here we change the method to get -->
<form action="chord/details.php" method="get" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
<?php
foreach ($songTitle as $song) {
// we add the id to the link
echo "<a href='chord/details.php?id={$song['id']}'>{$song['title']} <br> </a>";
}
?>
And change the detail.php like below:
<?PHP
//This is working fine with Search Bar
require_once '../config.php';
if (isset($_GET['search']) OR isset($_GET['id'])) {
$condition = "";
$value = "";
if (!empty($_GET['id'])) {
$condition = "id = :value";
$value = $_GET['id'];
}
elseif (!empty($_GET['search'])) {
$condition = "title = :value";
$value = $_GET['search'];
}
$sql = 'SELECT * FROM song WHERE ' . $condition;
$stmt = $conn->prepare($sql);
$stmt->execute(['value' => $value]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>
It's also a good idea to use LIKE for searching in the title like below:
if (!empty($_POST['search'])) {
$condition = "title LIKE :value";
$value = "%" . $_POST['search'] . "%";
}

Assuming you have an id column in the song table. You could do something like this:
<?php
require_once '../config.php';
$sql = 'SELECT id, title FROM song ORDER BY title ASC;';
$stmt = $conn->prepare($sql);
$stmt->execute();
// fetch all rows
$songTitle = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
//Search bar
<form action="chord/details.php" method="post" class="p-3">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control form-control-lg rounded-0 border-primary width =250px;" placeholder="Search..." autocomplete="off" required>
<div class="input-group-append">
<input type="submit" name="submit" value="Search" class="btn btn-primary rounded-right">
</div>
</div>
</form>
// Here I display all my songs from the database using their title
<?php
foreach ($songTitle as $song) {
// I'm not sure how to modify here.
echo "<a href='chord/details.php?id=".$song['id]."'>{$song['title']} <br> </a>";
} ?>
Details page
//This is working fine with Search Bar
<?php
require_once '../config.php';
if (isset($_POST['submit'])) {
$title = $_POST['search'];
$sql = 'SELECT * FROM song WHERE title = :title';
$stmt = $conn->prepare($sql);
$stmt->execute(['title' => $title]);
$row = $stmt->fetch();
} elseif (!empty($_REQUEST['id'])) {
$sql = 'SELECT * FROM song WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $_REQUEST['id']]);
$row = $stmt->fetch();
} else {
header('location: .');
exit();
}
?>
//Display the song lyrics here
<div>Original Key: <?= ucfirst($row['chord']) ?></div><br>
<pre data-key=<?= ucfirst($row['chord']) ?> id="pre">
<?= ucfirst($row['lyrics']) ?>
</pre>

Related

How to get my custom URL to the URL browser when Search Data

I think from the title its not really clear so I'm goning to explain it here, I got an URL like this => localhost/restoq/?page=Laporan, but when I tried to search it with my query its only show localhost/restoq/?search=example. So what I need to do to get the "?page=Laporan into my URL?
Form :
<form action="" method="GET">
<div class="form-row">
<div class="col-md-12">
<label for="">Keyword</label>
<input type="text" name="search" class="form-control" placeholder="Masukkan Keyword" value="<?php if(isset($_GET['search'])) { echo $_GET['search']; } ?>" />
</div>
</div>
<div class="form-row mt-3 float-right">
<button type="submit" class="btn btn-danger">Search</button>
</div> </form>
Query :
if(isset($_GET['search']) ) {
$keyword = $_GET['search'];
$query = "SELECT barang.kode, barang.nota, barang.tgl_input, barang.no_inv, barang.status_doc, barang.posisi_doc, barang.no_po, barang.nilai, users.nama FROM barang INNER JOIN users ON barang.id_user = users.id_user
WHERE barang.nota like '%".$keyword."%'
OR tgl_input like '%".$keyword."%'
OR status_doc like '%".$keyword."%'
OR posisi_doc like '%".$keyword."%'
OR no_inv like '%".$keyword."%'
OR no_po like '%".$keyword."%'
OR nilai like '%".$keyword."%'
ORDER BY barang.kode ASC";
} else {
$query = "SELECT barang.kode, barang.nota, barang.tgl_input, barang.no_inv, barang.status_doc, barang.posisi_doc, barang.no_po, barang.nilai, users.nama FROM barang INNER JOIN users ON barang.id_user = users.id_user ORDER BY barang.kode ASC";
}
Change the form tag to something like:
<form action="?search=<?php print $_GET['search']; ?>" method="GET">
Full example:
<html>
<body>
<?php
error_reporting(E_ALL);
if (!empty($_GET['reset'])) {
header('Location: /index.php');
exit();
}
function search(string $string)
{
return [
'result1',
'result2',
'result3',
];
}
function real_escape_string($value)
{
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
$results = [];
if (!empty($_GET['search'])) {
$results = search(real_escape_string($_GET['search']));
}
?>
<form action="?search=<?php print $_GET['search']; ?>" method="GET">
<input type="text" name="search" value="<?php !empty($_GET['search']) ? $_GET['search'] : ''; ?>">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="reset" value="Reset">
</form>
<?php
if ($results) {
?>
<h2>Results</h2>
<div class="results">
<?php
foreach ($results as $result) print '<br>' . $result;
?>
</div>
<?php
}
?>
</div>
</body>
</html>

Warning: Invalid argument supplied for foreach() HTML embedded

I have made a basic search engine and I try, to fetch the results, on the same page; moreover, the results have been retrieved and stored in the associative array, but the embedded code in HTML shows only one record, of the results. `
<?php
require('Configuration/config.php');
require('Configuration/db.php');
//If the user clicks, on the button search, the execute the query
if (isset($_POST['search_btn'])) {
$search_query = $_POST['search'];
//$search_query = htmlspecialchars($_POST['search']);
//Create the query.
$query = "SELECT * FROM The_primary_arkivum WHERE
Name = '$search_query' OR
Address = '$search_query' OR
Category = '$search_query' OR
Country = '$search_query' OR
State = '$search_query'";
//Get the results.
$results = mysqli_query($conn, $query);
//Fetch the data, of the result, to an array.
$search_results = mysqli_fetch_all($results, MYSQLI_ASSOC);
//var_dump($search_results);
//var_dump($search_query);
//Free result
mysqli_free_result($results);
//Close the connection
mysqli_close($conn);
}
?>
<?php include('included/header.php'); ?>
<body>
<div class = "header">
<h2>Search</h2>
</div>
<form method="post" action="search_index.php">
<div class="input-group">
<label>Search</label>
<input type="text" name="search" value="<?php echo $search; ?>">
</div>
<div class="input-group">
<button type="submit" class="btn" name="search_btn">Search</button>
</div>
<?php foreach($search_results as $search_result) : ?>
<div class="mySlides fade">
<?php echo $search_result['Name']?>
<?php echo $search_result['Address']?>
<?php echo $search_result['Country']?>
</div>
<?php endforeach; ?>
</form>
<?php include('included/footer.php'); ?>
`
Your echo statements in your form do not have ending semicolons ;. Try starting there.
<?php echo $search_result['Name'];?>
<?php echo $search_result['Address'];?>
<?php echo $search_result['Country'];?>

My PHP Code is Not Updating Values In Database

I have tried to write a code that update category in the database using admin panel but whenever i try to do that it won't work and i don't get any errors to look into it, please help guys; thanks a lot
PHP Code:
<?php
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE category_id = $edit_id ";
$edit_get_result = mysqli_query($connection,$query);
if (!$edit_get_result) {
die("Edit Get Result Query FAILED");
}
while ($category_name_row=mysqli_fetch_assoc($edit_get_result)) {
$category_name = $category_name_row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
}
?>
Please check below code. You need to pass edit_id in your form POST. I have put it in a hidden input and set it's value according to the GET parameter from top of your php part.
<?php
if (isset($_GET['edit'])) {
$edit_id = mysqli_real_escape_string($connection,$_GET['edit']);
$query = "SELECT * FROM categories WHERE category_id = '$edit_id' ";
$result = mysqli_query($connection,$query);
if(!$result) {
die("Edit Get Result Query FAILED");
}
while ($row=mysqli_fetch_assoc($result)) {
$category_name = $row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<input type="hidden" name="edit_id" value="<?php if(isset($edit_id)) echo $edit_id;?>">
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit']) && isset($_POST['edit_id'])) {
$category_name = mysqli_real_escape_string($connection,$_POST['update_category']);
$edit_id = mysqli_real_escape_string($connection,$_POST['edit_id']);
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$result = mysqli_query($connection,$query);
if (!$result) {
die("Final Update Query Result FAILED");
}
else echo "Final Update Query Result Success";
}
?>
Hi have noticed that you have used raw inputs. try avoiding it. Also noticed your code had extra curly braces at the end.
Please try using the following code after replacing your end page section php script.
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
And Change your query variable to the following:
$query = "SELECT * FROM categories WHERE category_id = ".$edit_id;

Insert, Update, Search in MySql database using PHP

This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.

Dealing with search query and action

I did a search feature that will enable users to search and see result from database.
First - I want to transfer the search query (What the user searched for) into the search action (searchact.php)
When A user fills the input field below (form) and hit search...
<form action="searchact.php" class=" form-inline" method="post">
<div class="form-group">
<input type="text" name="word" class="form-control" placeholder="House key word">
</div>
<div class="form-group">
<select name="location" class="form-control">
<option value="Bosso">Bosso Campus</option>
<option value="GK">Gidan Kwano Campus (GK)</option>
</select>
</div>
<div class="form-group">
<select name="price" class="form-control">
<option>10-49k</option>
<option>50-99k</option>
<option selected>100-149k</option>
<option>150-199k</option>
</select>
</div>
<input type="submit" class="submit" name="submit" value="Search...">
</form>
I want the next page url (searchact.php) to be something like
wwww.test.com/searchact.php?q=word&location=Bosso&price=10-49k
This is searchact.php
<?php
if($_POST["submit"])
{
$word = $_POST["word"];
$location = $_POST["location"];
$price = $_POST["price"];
$sql = "INSERT INTO search (word,location,price) VALUES (:word,:location,:price)";
$q = $connecDB->prepare($sql);
$q->execute(array(':word'=>$word, ':location'=>$location, ':price'=>$price));
if($q)
{
$query = "SELECT * FROM house WHERE location LIKE :location AND tag LIKE :info AND range LIKE :range order by id desc LIMIT 10";
$stmt = $connecDB->prepare($query);
$stmt->bindValue(':info', '%' . $word . '%', PDO::PARAM_INT);
$stmt->bindValue(':location', '%' . $location . '%', PDO::PARAM_INT);
$stmt->bindValue(':range', '%' . $price . '%', PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$result = $stmt->fetchAll();
foreach( $result as $row ) {
$hid=$row["id"];
$name=$row["name"];
?>
<!--Some Html-->
<?php
}}
else {
echo 'No result found';
}
}}
?>
2nd - How do I make sure that a user actually searched for something without manually visiting "searchact.php"
Like.. How do I redirect a user to an error page when they just visit the searchact.php without inputing any search query.

Categories