GET and POST in PDO - php

I have problem in sample page that will retrieve student id from the url ' update.php?id=1' to use it in query , when I write the id manually in the query it's worked .. can't figured out
update.php
<?php
require 'database.php';
$id=$_GET['id'];
if (!empty($_POST)) {
$name=$_POST['name'];
$mobile=$_POST['mobile'];
$pdo=Database::connect();
$sql="UPDATE students SET name=? , mobile=? WHERE id=?";
$q=$pdo->prepare($sql);
$q->execute(array($name,$mobile,$id));
Database::disconnect();
header('Location: index.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<div>
<div>
<h3>Update Student Information</h3>
</div>
<form action="update.php" method="post">
<div>
<label>Name</label>
<div>
<input name="name" type="text">
</div>
</div>
<div>
<label>Mobile No.</label>
<div>
<input name="mobile" type="text">
</div>
</div>
<div>
<button type="submit">Add</button>
Back
</div>
</form>
</div>
</div>
</body>
</html>
UPDATE : To make this clear the id retrieve from url address from other page like I said not from the html form ... url ' update.php?id=1' how should I do it ?
index.php
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM students';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['mobile'] . '</td>';
echo '<td>Show</td>';
echo '<td>Update</td>';
echo '</tr>';
}
Database::disconnect();
?>

To see what error the PDO throws, add the following code:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
also you should add these (at the top of your file):
ini_set('display_errors', 1);
ini_set('display_startup_errors',1);
error_reporting(-1);
Another idea: Maybe the stuff from post is empty?

Why not send the id variable with the POST form as well?
<input type="hidden" name="id" value="x">
Then retrieve it with $_POST['id'] instead of $_GET['id']

your didnt use $id in your query
it should be some thing like $sql="update students SET name=? , mobile=? WHERE id=".$id." "

Related

Deleting multiple rows using checkbox

I have this code
<html>
<head>
<meta charset="UTF-8">
<title> Game Library</title>
<link href="css/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<div id="search">
<img id="del" src="img/delete.jpg" alt="Error">
<a class="A" href="index.php"><img class="AR" src="img/src.jpg" title="Search library"></a>
<a class="A" href="insert.php"><img class="AR" src="img/add.png" title="Add game"></a>
<div id="results">
<?php
require("inc/connection.php");
$query = "SELECT * FROM Library";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
?><div id="results">
<form action="inc/delete.php" method="GET">
<input type="checkbox" name="checkbox[]" value="<?php echo $row['ID'] ?>">
<p id="p1">Name: <?php echo $row['Name']?>;</p>
<p>Genre: <?php echo $row['Genre']?></p>
<p>Release date: <?php echo $row['Release_date']?></p>
<p>Publisher: <?php echo $row['Publisher']?>:</p>
<p>Platforms: <?php echo $row['Platforms']?></p>
</div>
<?php
}?>
<input type="submit" name = "submit" value = "Submit"></form>
<?php
}else{
echo "No results!";
}
</div>
</div>
</div>
</body>
</html>
And I am supposed to create action="inc/delete.php" script which will allow me to delete multiple rows using checkbox and submit button. Can someone help me out with this please ? I honestly have no clue on how to complete this ....
<?php
if(isset($_POST['submit']))
{
if(!empty($_POST['checkbox']))
{
foreach ($_POST['checkbox'] as $key => $check)
{
// delete query
}
}
}
?>
NOTE: You failed to close PHP at line no. 40. Please make sure your PHP tag is closed or not.
Need to first set form method to `POST'
So, modify
<form action="inc/delete.php" method="GET">
To:
<form action="inc/delete.php" method="post">
And in inc/delete.php,
if (isset($_POST['submit'])){ // Check if form is submitted.
if (! empty($_POST['checkbox'])){ // Check if Checkbox is checked.
// Loop over the checkbox and get selected ids.
foreach($_POST['checkbox'] as $checkbox_id){
echo $checkbox_id."<br/>";
// Add your delete query here.
}
}
}
So the resolution is that you get at your delete script array of ids. You can parse that array and execute DELETE query for each id:
if(isset($_POST['checkbox']))
{
foreach($_POST['checkbox'] as $val)
{
$stmt = $conn->prepare("DELETE FROM Library WHERE id = ?");
$stmt->bind_param('i', $val);
$stmt->execute();
}
}
inc/delete.php
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['checkbox'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['checkbox'] as $row_id){
echo $row_id."</br>";
// DELETE QUERY HERE
}
}
}
?>

Getting a value from a database and echoing from another file

I am trying to Select a row from a database table and display the variables in another PHP file. Right now I have to trying just one variable, but will change to outputting a table later on. The error is an Undefined Variable:output.
I have tried using session but it prints out the array and doesn't go all the way through. I really just want the variable so that I can put them into a table easier.
My store file, which shows a search bar and where I am trying to display the results, under the search bar.
<?php
require "header.php";
?>
<main>
<form action="includes/itemsearch.php" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>
<?php
require "footer.php";
?>
My item search file:
<?php
if (isset($_GET['search-submit'])) {
require 'connect.php';
$item = $_GET['item'];
$output = "";
$sql = "SELECT * FROM Product";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$pName =$row['Product_Name'];
$manufacture=$row['Manufacture'];
$quantity=$row['Quantity'];
$price=$row['Price'];
$description=$row['Description'];
echo"<p>$pName</p><br />";
}
header("Location: ../store.php?");
}
I currently get an undefined variable error.
use post method instead of get
<?php
if (isset($_POST['search-submit'])) {
}
?>
$output is undefined because you initialize it on click of submit button so <?php echo $output ?> is executing first then it gets initialized.
try
<?php
if (isset($_GET['search-submit'])){
echo $output;
}
?>
to get output just require search file in store.php
// store.php
<?php
require "header.php";
require "search.php";
?>
<main>
<form action="" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>
<?php
require "footer.php";
?>
this is the final code
// search.php
<?php
if (isset($_GET['search-submit'])) {
require 'connect.php';
$item = $_GET['item'];
$output = "";
$sql = "SELECT * FROM Product";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$pName =$row['Product_Name'];
$manufacture=$row['Manufacture'];
$quantity=$row['Quantity'];
$price=$row['Price'];
$description=$row['Description'];
$output .= "<p>$pName</p><br />";
}
}
?>
// store.php
<?php
require "header.php";
require "search.php";
?>
<main>
<form action="" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo isset($_GET['search-submit']) ? $output : '' ?>
</main>
<?php
require "footer.php";
?>

Print out table details from database

I am trying print out a table that has student testimonials and I want to print out the ID, title, text and student ID but when hit the "search_all" button, I am told that it can't fetch mysqli and I am not sure what to do.
<?php ("session.php"); ?>
<?php require_once("connect.php"); ?>
<?php include("header.php"); ?>
<html>
<body>
<!-- Page Content -->
<h1 class="page-header">Learning Journals
<small>- Admin Search</small>
</h1>
<h3>Search Learning Journals</h3>
<form name="membership_form" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="contactForm" method="post">
<label>Search Journals ID:</label>
<br>
<input type="text" name="journal_search">
<br>
<button type="submit" name ="search_all" class="btn btn-primary">All Journals</button>
</form>
<?php
if(isset($_POST["search_button"]))
{
//create the sql statement
$sql_all= "SELECT * FROM testimonials";
$result = mysqli_query($con,$sql_all);
while ($row = mysqli_fetch_assoc($result))
{
echo
"<h4>Testimonial ID:</h4>". $row["testimonial_ID"].
"<h4>Title:</h4> ". $row["testimonial_title"].
"<h4>Text:</h4> ". $row["testimonial_text"].
"<h4>Student ID:</h4>". $row["student_ID"].
"</br>";
}
mysqli_close($con);
}
include("footer.php");
?>
</body>
</html>

How to make PHP drop down menu be taken as a HTML form input

So I've made a drop down menu (using PHP), and I'm not sure how to make it so that it can be taken as an input into a HTML form?
This is the PHP code:
<?php
$dropdownsql = "SELECT prodName FROM tblProduct";
$dropdownresult = #mysqli_query($connect, $dropdownsql);
echo "<select name='prodID'>";
while ($row = mysqli_fetch_array($dropdownresult, MYSQLI_ASSOC)) {
echo "<option value='" . $row['prodID'] . "'>" . $row['prodName'] . "</option>";
}
echo "</select>";
?>
And this is the HTML form code:
<form action="addOrder.php" method="post">
<p>
Order Date*:
<input type="text" name="orderDate" maxlength='70' required>
<p>
Order Location*:
<input type="text" name="orderLocation" maxlength='255' required>
<p>
Order Product*:
<p>
Order System*:
<input type="text" name="orderSystem" required>
<p>
<input type="submit" name="submit" value="Add Order">* Means that the field is required.
<input type="hidden" name="submitted" value="TRUE">
</form>
*Note that I want the input for Order Product
I have rewritten this to make it secure. Check if it works for you:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Link Games</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'header.php';
include 'menu.php';
try {
$connect = new PDO("mysql:dbhost=localhost;dbname=linkgamesDB", 'username', 'password');
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
<div id="content">
<p class="headers"><strong>Add Order</strong></p>
<?php
#Check that the form is submitted
if (isset($_POST['submitted'])) {
#Create then run the query
$query= $connect->prepare("INSERT INTO tblOrder(orderDate, orderLocation, orderProd, orderSystem) VALUES (?, ?, ?, ?)")
$query->bindValue(1, $_POST['orderDate']);
$query->bindValue(2, $_POST['orderLocation']);
$query->bindValue(3, $_POST['orderProd']);
$query->bindValue(4, $_POST['orderSystem']);
$query->execute();
#Check if there is an error in query and display relevant message
if ($query->rowCount() > 0) {
echo '<p class="records">Thank you! Record Added.</p>';
} else {
echo '<p class="records">Error. No record added.</p>';
}
}
?>
<form action="addOrder.php" method="post"><p>
Order Date*: <input type="text" name="orderDate" maxlength='70' required><p>
Order Location*: <input type="text" name="orderLocation" maxlength='255'required><p>
Order Product*: <select name='orderProd'>
<?php
$dropdownsql = $connect->prepare("SELECT prodID, prodName FROM tblProduct");
$dropdownsql->execute();
$r = $dropdownsql->fetchAll();
foreach($r AS $row):
?>
<option value="<?php echo $row['prodID'];?>"><?php echo $row['prodName'];?></option>
<?php endforeach;?>
</select>
<p>
Order System*: <input type="text" name="orderSystem" required><p>
<input type="submit" name="submit" value="Add Order"> * Means that the field is required.
<input type="hidden" name="submitted" value="TRUE">
</form>
</div>
</body>
</html>

Session not passing POSTed data to second script - please advise

Tried asking this, it was marked duplicate with a suggestion. I employed the suggestions which still do not seem to be performing the desired result. Could someone actually read the following and advise where I am going wrong?
I am attempting to use sessions to pass the user selected data from this script (allotment.php) to a subsequent script (allotmentreport.php) wherein it is used in a query qualifier (e.g. ...WHERE tablecolumndata=session variable...). I am not getting an error from allotment.php upon selecting the option and clicking SUBMIT but data fails to pass to allotmentreport.php and returns an error for an undefined variable.
Is this and the line after it correct? Is there something I am missing otherwise?
$tourselect=(isset($_POST['submit']));
UPDATE The final and corrected code is displayed below for future users seeking a working example and easy to read solution:
<?php
session_start();
$host="localhost";
$username="HIDDEN";
$password="HIDDEN";
$dbname="bookings2015";
$con = mysql_connect($host, $username, $password, $dbname);
if (!$con)
{
die ('damn thing wont connect to the MYSQL server: Maybe it is retarded '. mysql_error());
}
mysql_select_db($dbname, $con);
?>
<!Doctype html>
<html>
<?php include 'C:\xampp\htdocs\phpproject1\head.php';
include 'config\menu.php';
?>
<div id="dataentry">
<div id="submit">
<?php
echo "Which Tour to check availability? ";?>
<br />
<br />
</br>
</br>
<form method="post" action="allotment_report.php">
<select name='TourCode'>
<?php
$tourselection = "SELECT DISTINCT TourCode FROM toursanddates ORDER BY TourCode";
$result = mysql_query($tourselection);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['TourCode'] . "'>" . $row['TourCode'] . "</option>";
}
?>
</select>
<input type="submit" name="tourselected" value="submit">
</form>
<?php
?>
</div>
</div>
<div id="demographicborder">
<?php
include 'footer.php';?>
</div>
</div>
</body>
</html>
</form>
</form>
</div>
</div>
</div>
</body>
</html>
and here is the allotment_report.php code
<?php
session_start();
$host="localhost";
$username="STILLHIDDEN";
$password="STILLHIDDEN";
$dbname="bookings2015";
$con = mysql_connect($host, $username, $password, $dbname);
if (!$con)
{
die ('damn thing wont connect to the MYSQL server: Maybe it is retarded '. mysql_error());
}
mysql_select_db($dbname, $con);
include 'C:\xampp\htdocs\phpproject1\head.php';
include 'config\menu.php';
?>
<br />
<br />
<?php
//Table Header:
echo " <strong><u>Tour Availability</u>";
echo '<table align="center" cellspacing="3" cellpadding="3" width="75%">
<tr>
<td align=:"left"><b>Tour:</b></td>
<td align=:"left"><b>Start Date:</b></td>
<td align=:"left"><b>Seats Avail:</b></td>
<td align=:"left"><b>Rooms Avail:</b></td>
</tr>
';
if(isset($_POST['TourCode'])){
$tour=$_POST['TourCode'];
}
$status="ok";
$ar="SELECT TourCode, DATE_FORMAT (TourStart, '%m%d%y') AS TourStart, SeatsAvail, RoomsAvail FROM toursanddates WHERE TourCode='$tour' AND Status='$status' ORDER BY TourCode, TourStart ASC";
$result=mysql_query($ar);
$num_results = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
//Display the allotments fetched in above query
echo '<tr>
<td align=:"left">' . $row['TourCode'] . '</td>
<td align=:"left">' . $row['TourStart'] . '</td>
<td align=:"left">' . $row['SeatsAvail'] . '</td>
<td align=:"left">' . $row['RoomsAvail'] . '</td>
</tr>
';
}
echo '</table>';
//echo "</strong>Tour: ".($row['TourCode']);
//echo "</strong> Start Date: ".($row['TourStart']);
?>
<br />
<?php
echo "<br />";
echo "</p>";
?>
</br>
</br>
</div>
</form>
</div>
<div id="demographicborder">
<?php include 'footer.php';
?>
</div>
</div>
</body>
</html>
</form>
</form>
</div>
</div>
</div>
</body>
</div>
</body>
<?php
//contained within allotment.php
$tourselect=(isset($_POST['tourselected']));
$_SESSION['tourselected']=$tourselect;
?>
It looks like you are expecting $_SESSION['tourselected'] to be set on allotment.php the when a user loads opens the page for the first time. However this is not the case. $_POST data is attached with an HTTP request. When you load alloment.php for the first time, the browser doesn't send any $_POST data to it. This would explain why $_SESSION['tourselected'] is unset when you get to your second script.
That said, if your only goal is to send data from the form built in alloment.php to alloment_report.php you shouldn't be using sessions at all. All of this can be done with only $_POST.
consider the following code:
<!--alloment.php-->
<form method="post" action="alloment_report.php">
<select name='TourCode'>
<?php
//Assume that $options contains stuff pulled from your database.
foreach($options as $option) {
echo "<option value='" . $option . "'>" . $option . "</option>";
}
?>
</select>
<input type="submit" name="tourselected" value="submit">
</form>
When a user completes the form, and clicks submit, alloment_report.php (specified by action="alloment_report") gets the data sent from the form over $_POST (specified by method="post").
<!--alloment_report.php-->
<?php
if(isset($_POST['tourcode'])){
echo "yay! the tour has been selected!";
}
?>

Categories