Button to post value from fetched database data - php

I'm a beginner in PHP and PDO.
I'm trying to fetch database data from a database table, display it on a list and add a button that when clicked it adds the itemid value to another table with the name_id of the user.
The issue is even though the list is displaying the items in order and correctly,the button is not working 100%, when pressed on any item from the list it always posts the first itemid value from the database column.
Any help is appreciated.
echo ''.$itemid.'';
echo'<form action="" method="post"><button name="get" type="submit">CLICK ME</button></form>' ;
if(isset($_POST['get'])){
$query = "update table set fetched_item_id='".$row['item_id']."' where name_id='".$_SESSION['id']."' ";
if($query)
{
$query = $conn->prepare($query);
$query->bindParam('1', $itemid);
$query->execute();
echo "Success!";
exit;
}
I tried everything I could according to my knowledge.

Related

Using searchbox to query same data as dropdown

I am currently developing an application which allows the user to pick an option from a dropdown, and list table data based on this option, and done so dynamically. I was pondering the thought of a search bar which allows the user to search for a country name (within a continent) and list said country name upon searching. The part which confuses me is can I make it so that the user can pick a continent from the dropdown, and input a country name into the search bar then click the same button and receive the listing?
I understand the importance of picking relevant code however I think it would be important for the reader to see both my home page, and action page to understand what I am trying to achieve.
Here is the index code:
require_once('repeat_code.php');
$db = dbConn();
//Make an SQL statement
$sqlContinents = "SELECT DISTINCT ID as contID, Name as contName from w_Continent order by contName;";
//Execute SQL statement
$stmt = $db->query($sqlContinents);
//Start a form
echo "<form action='listCont.php' method='get'>\n";
//Start a select box
echo "<select name='contID'>\n";
//Loop through all continents
while ($continent = $stmt->fetchObject()) {
//Display each one as an option in the dropdown
echo "\t\t<option value='{$continent->contID}'> {$continent->contName} </option>\n";
}//end loop
// end select box
echo "</select>\n";
// display submit button
echo "<input type='submit' value='Find Country' />\n";
// end form
echo "</form>\n";
Here is the action page:
if(!empty($contID)) {
//Connect to the database
require_once('repeat_code.php');
$db = dbConn();
//Create SQL statement using ID
$sqlCountries = "SELECT w_Country.Name, w_Continent.Name as 'contName', w_Country.Region as 'regionname', w_Country.HeadOfState, w_Country.Capital
FROM w_Continent JOIN w_Country on w_Continent.ID = w_Country.Continent
WHERE w_Continent.ID = '$contID'";
//Execute statement to get a record set back
$stmt = $db->query($sqlCountries);
// Start a table
echo "<table border='1'>\n";
// Start a header row
echo "<tr><th>Country</th><th>Continent</th>\n";
//Loop through the record set
while ($continent = $stmt->fetchObject()) {
//Display each student in a row
echo "\t<tr><td>{$continent->Name}</td><td>$continent->contName</td>\n";
}//End loop
//end the table
echo "</table>";
Any help is appreciated.
Create a drop down and input box in a single line.
Drop Down Contain the continent and input box is empty.
In database create 2 tables in following format.
Continent Table
id | Continent_name
Countries Table
id | country_name | continent_id
Now run query in first table and display all the continent in drop down.
now when user select the continent name from the drop down and also write country name in the search box, then you have to query like this.
<form method="post">
<input type="hidden" name="command" value="search">
<select name="select_box">
<option value ="1">Asia</option>
<option value ="2">Africa</option>
</select>
<input type ="text" name="search_box" placeholder="Type Country">
</form>
Now Run PHP code like below.
if($_REQUEST['command']=='search'){
$continent_id = $_REQUEST['select_box']; //suppose user select asia
$country_name = $_REQUEST['search_box']; // suppose user type "Pakistan"
//now execute below query in countries table.
$query ="select * from countries where continent_id='$continent_id' and country_name like '%$country_name%'";
}

Filter MySQLi with checkboxes

At the moment, I have a page that is displaying some posts. News posts, blog posts etc. What I want to achieve is having checkboxes so the user can check off, whatever kind of post he/she wants to see.
I should for instance be able to check off ´news´ and ´talking points´ and only see posts with those categories, and not see posts with the category ´blog´ for instance.
My current query looks like this (gets all posts, no matter the category). I believe some jQuery should be involved but I am not sure. How can I connect checkboxes with the query?
Can anyone help me with this?
$sql = "SELECT * FROM articles ORDER BY id DESC";
EDIT
I have tried this, but whenever I use the checkboxes, nothing is shown but I do not get an error?
My code:
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
$categories = $_POST['check_list'];
// Loop to store and display values of individual checked checkbox.
foreach($categories as $selected){
echo $selected."</br>";
}
}
}
?>
<br /><br />
<?php
if(!empty($_POST['check_list'])){
$sql = "SELECT * FROM articles ORDER BY id DESC WHERE `category` IN (".implode(',',$categories).")";
} else {
$sql = "SELECT * FROM articles ORDER BY id DESC";
}
Each checkbox should have a value. When you submit your form (probably a $_POST) you will see on the backend which checkboxes are checked. You can inspire from this tutorial: https://www.formget.com/php-checkbox/
IMPORTANT - You should filter the form data before using it in your SQL query. You can inspire from here: http://php.net/manual/en/function.filter-input.php
And you should prepare the variable before using it in the SQL Query:
$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);
Now that you know which checkboxes are checked, you need to change the SQL query in order to filter by them.
So I suppose the checkboxes values are numbers (representing id's). So you will have an array called $ids that will contain all the checked checkboxes. Your mysql query will become something like:
$sql = "SELECT * FROM articles WHERE `id_category` IN (".implode(',',$ids).") ORDER BY id DESC";

Print specified page, update DB MYSQL and PHP

I have the following code:
<iframe onscroll ="caise4.php" name="frame4"></iframe>
<input type= "submit" onclick ="frames['frame4'].print()" value = "WATER/ELECTRICITY" id = "id4"></a>
This would allow me to print a different page when the button/frame is clicked.
And i have the following PHP code:
<?php
if(isset($_POST['frame4'])){
$SQL_1 = "INSERT INTO `tick4` (`ticket_id`, `ticket_date`) VALUES (NULL, CURRENT_TIMESTAMP)";
$result_1 = mysqli_query($db, $SQL_1);
$SQL_2 = "UPDATE v_attente_service AS vas
JOIN (SELECT COUNT(ticket_id) AS cnt FROM tick4) AS ti
SET vas.NOMBATTE = ti.cnt
WHERE vas.CODESERV=4";
$result_2 = mysqli_query($db, $SQL_2);
}
?>
When the user clicks, a new row needs to be inserted in the table "tick4". Then "NOMBATTE" in "v_attente_service" is updated.
Basically, when the user prints a ticket, the number of tickets is updated, and the number of people waiting in the queue is also updated.
The problem I have: I get redirected to the page preview, but nothing is displayed there. Also, nothing gets updated in my tables.
I am using phpMyAdmin by the way.
Any help would be greatly appreciated. Thank you.

Link next to each row in sql table result in php to display full data for that row

I am trying to display couple of fields from sql table and want to add a link in each row that takes user to a page that shows all results for that specific table row.
Let me explain more: I have a MySql table that has the following fields: filename, intro_data, content_data, conclusion_data. I have created a php page that displays the list of all data for the filenames & intro_data fields in that sql table using this code:
//Query to select rows or data in table
$query= "SELECT filename,intro_data FROM file_data";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
echo '<table border="1">'; // start a table tag in the HTML
//Storing the results in an Array
while ($row = mysqli_fetch_array($result)) //Creates a loop to loop through results
{
echo "<tr><td>" . $row['filename'] . '</td><td>' . $row['intro_data'] . '</td><td> More Info</td></tr>';
}
echo '</table>'; //Close the table in HTML
//Closing DB Connection
mysqli_close($connect);
If you noticed in the above code, I have a "More Info" anchor tag that links to 'full_table_row_results.php'. In this page, I want it to show all the field results (filename, intro_data, content_data, conclusion_data) for that particular row. I know that I can query all results for a table like this:
$query= "SELECT * FROM file_data";
But how can I create the 'full_table_row_results.php' that queries all fields for that particular row that the user is clicking on? Since the row results are from an array, how do I know which row number in that array has the user clicked on? I am not sure how to code the More Info page.
I am stuck on this and not sure how to implement this.
One solution (as always, there's many other).
First, you need an id for each row in your table (if you do not have already one). With MySQL an auto_increment integer field does the job.
Next, you need to get the id in your php code.
$query= "SELECT id, filename,intro_data FROM file_data";
Then you use it as a parameter when you link to your full_table_row_results.php script. The link will be:
echo '<a href="full_table_row_results.php?id=' . $row['id'] . '">' /* etc. */ ;
(Adapt it in your code, I did not copy all your code to easier readability).
And in this last script you get access to this parameter with $_GET['id']. Then you can query your database for this one row only (with a WHERE clause).
Hope this help

Retrieve a table from DB using php and then choose a specific item

My header is probably ambiguous so i'm gonna explain it.
I have a table "books" in my database. I need to retrieve the table using php and then choose the book and comment about the book.
I got the retrieving part, a table with all my books is displayed.
I am stuck with selecting the book part.
Here is what i need to do:
Retrieve the table "books" from DB
Choose some book from that table (i.e. dropdown list etc)
Press submit and go to another page where I can leave a comment about that book
The comment must be recorded in DB
I just need help with selecting the book from the table. How to do it?
let me assume you have a these rows in the table book
book_id(PI), name author
<form method="post" action="something.php">
<select name="book">
<?php
$stmt = $mysqli->prepare("SELECT id,name,author FROM books");
if($stmt) {
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
echo '<option value='.$myrow['book_id'].'>'.$name.' '.$author.'</option>';
}
//instead of $result you can also do
if($stmt) {
$stmt->execute();
$stmt->bind_result($id,$name,$author):
while ($stmt->fetch()) {
echo '<option...
}
?>
if you want both the id and name or all of the three go to this link
if you want to select your books on certain criteria, for example lets say author=enid
then modify the query like this:
$stmt = $mysqli->prepare("SELECT id,name,author FROM books WHERE author=?");
if($stmt) {
$stmt->bind_param("s",$input_name);
$stmt->execute();
.....
then at the something.php use the $_POST[''] to get the user inputs.
then u can make a form use a hidden value with a value= id of the book
make a comment box
use a submit button.
then in another table 'comments' u can have two rows comment_id(PI) book_id and comment
then use the insert query
$stmt=mysqli_prepare("insert into comments (book_id,comment) values (?,?)");
if($stmt) {
$stmt->bind_param('is',$book_id,$comment);
$stmt->execute();
}
always remember to use $stmt->close() and $stmt->free() . how to do that will be answred by php.net

Categories