Trying to access certain information from database - php

I asked this question before but did not get any actual answers. I created a website for my wife's jewelry. She wants a product page for each style she makes (bracelets, necklaces, etc.).
I created the database with a category section that has all the different categories she makes. The only problem I have is I cannot get the information to show up on the product page. I get errors such as
Notice: Undefined variable: item_number in C:\xampp\htdocs\pinkys_pearls\bracelets.php on line 83.
Here is my code for the page:
<?php
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
?>
<?php
// Connect to the MySQL database
include_once("storescripts/connect_to_mysql.php");
$con = mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
//Initializing variable
$item_number = "item_number";
$description = "description";
$category = "category";
$price = "price";
$qty = "qty";
$sql = "SELECT category FROM products WHERE category='Bracelets';";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
// get all the product details
while($row = mysqli_fetch_assoc($result)); {
echo $item_number = $row["item_number"];
$price = $row["price"];
$desc = $row["description"];
$category = $row["category"];
}
}
else {
echo "Data to render this page is missing.";
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Bracelets</title>
<meta charset="utf-8">
<meta http-equiv="x=UA-comparable" content="IE-edge">
<meta name="description" content="Pinky's Pearls is a website where one of a kind jewelry designed by Nichole <q>Nicki</q> can be seen and purchased">
<meta name="keywords" content="jewelry, beads, bracelets, rings, pendants, necklaces, pearls, crystal">
<meta name="viewpoint" content="width=device-width, initial-scale=1">
<meta name="author" content="samuel jaycox">
<link href="style.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="shortcut icon" type="image/png" href="pictures/pinky.png">
<script src="https://use.fontawesome.com/0c9491c5b9.js"></script>
</head>
<body>
<div align="center" id="wrapper">
<div id="banner-wrapper">
<!---Company Header-->
<header>
<div id="header">
<img class="bracelet_header" src="pictures/headers/bracelets.jpg" alt="Bracelets">
<audio autoplay="autoplay" loop="loop" id="background-music">
<source src="music/Albinoni-adagio-in-g-minor-acoustic-guitar.mp3" type="audio/mpeg">
<source src="music/Albinoni-adagio-in-g-minor-acoustic-guitar.wav" type="audio/wav">
</audio>
</div>
</header>
<!---end of Company Header-->
<br>
<?php include_once("templates/template_navigation.php"); ?>
<br>
<br>
<br>
<!--Start Comment page Body Content-->
<div id="body-content">
<div class="bracelet_body">
<table width="100%" border="2" cellspacing="0" cellpadding="15">
<tr>
<td width="19%" valign="top">
<img src="pictures/inventory/<?php echo $pid; ?>.png" width="142" height="188" alt="<?php echo $item_number; ?>" /><br />
View Full Size Image
</td>
<td width="81%" valign="top">
<h3><?php echo $item_number; ?></h3>
<p><?php echo "$".$price; ?>
<br /><br />
<?php echo $desc; ?>
<br />
</p>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" />
<input class="button" type="submit" name="button" id="button" value="Add to Shopping Cart" />
</form>
</td>
</tr>
</table>
</div>
</div>
<!--end of Comment body-->
<?php include_once("templates/template_footer.php"); ?>
</body>
</html>
What can I do to fix this?

You are missing a closing curly bracket at a critical point -
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
// RIGHT HERE
//Initializing variable
$item_number = "item_number";
$description = "description";
$category = "category";
With out it, none of your variables are initialized, your SQL query is never run, etc.
Once you've fixed that, try again and if there are still related issues edit the question, otherwise start a new question for a new issue.

Related

How can I download a file using a button from fetched row

I was able to fetch and display the data but I am unable to download the file using dowload button.
I am storing images inside a folder call images in root. [http://localhost/images/]
How can I actually download a file using this download button?
My Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Records</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
.bs-example{
margin: 20px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="bs-example">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left">Records</h2>
</div>
<?php
include_once 'dbconfig.php';
$result = mysqli_query($conn,"SELECT * FROM book");
?>
<?php
if (mysqli_num_rows($result) > 0) {
?>
<button type="Home" name="change" onclick="window.location.href='mgrmenu.php'">Home</button>
<table class='table table-bordered table-striped'>
<tr>
<td>Name</td>
<td>Age</td>
<td>Mobile</td>
<td>File</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["Fname"]; ?></td>
<td><?php echo $row["age"]; ?></td>
<td><?php echo $row["patientNo"]; ?></td>
<td><?php echo $row["images"];?><Button> Download</Button></td>
</tr>
<?php
$i++;
}
?>
</table>
<?php
}
else{
echo "No result found";
}
?>
</div>
</div>
</div>
</div>
</body>
</html>
How can I create my download button to actually download that particular file?
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
If you want to download any file on clicking a button you must try this:
<a class="btn" href="<?= $your_path_to_file ?>" download>Download File</a>

Images and product info not showing up on page

Been working on a product page for my wife's jewelry site. I added php from a tutorial and tried to run the page. None of the images including the header showed up along with the footer. They show up on every other page. None of the information product showed up either. the page says connection opened and i receive no errors. The navigation shows up along with some of the css but that is all.
Here is my code I am using.
<?php
error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
?>
<?php
if (isset($_GET['id'])) {
// Connect to the MySQL database
include_once("storescripts/connect_to_mysql.php");
$con =
mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
} $id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = "SELECT * FROM products WHERE category='Bracelets';";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
// get all the product details
while($row = mysqli_fetch_assoc($result)); {
$item_number = $row["item_number"];
$price = $row["price"];
$desc = $row["description"];
$category = $row["category"];
}
} else {
echo "Data to render this page is missing.";
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Bracelets</title>
<meta charset="utf-8">
<meta http-equiv="x=UA-comparable" content="IE-edge">
<meta name="description" content="Pinky's Pearls is a website where
one
of a kind jewelry designed by Nichole <q>Nicki</q> can be seen and
purchased">
<meta name="keywords" content="jewelry, beads, bracelets, rings,
pendants, necklaces, pearls, crystal">
<meta name="viewpoint" content="width=device-width, initial-scale=1">
<meta name="author" content="samuel jaycox">
<link href="style.css" rel="stylesheet">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
<link rel="shortcut icon" type="image/png" href="pictures/pinky.png">
<script src="https://use.fontawesome.com/0c9491c5b9.js"></script>
</head>
<body>
<div align="center" id="wrapper">
<div id="banner-wrapper">
<?php
include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_bracelets.php");
?>
<br>
<?php include_once("templates/template_navigation.php"); ?>
<br>
<br>
<br>
<!--Start Comment page Body Content-->
<div id="body-content">
<div class="bracelet_body">
<table width="100%" border="2" cellspacing="0" cellpadding="15">
<tr>
<td width="19%" valign="top"><img src="pictures/inventory/<?php echo
$pid; ?>.png" width="142" height="188" alt="<?php echo $item_number; ?>"
/>
<br />
<a href="pictures/inventory/<?php echo $pid; ?>.png">View Full Size
Image</a></td>
<td width="81%" valign="top"><h3><?php echo $item_number; ?></h3>
<p><?php echo "$".$price; ?><br />
<br />
<?php echo $desc; ?>
<br />
</p>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?php echo $id; ?
>"
/>
<input class="button" type="submit" name="button" id="button"
value="Add to Shopping Cart" />
</form>
</td>
</tr>
</table>
</div>
</div>
<!--end of Comment body-->
<?php include_once('templates/template_footer.php'); ?>">
</body>
</html>
Please make sure your paths are right!
Try to change your links
<?php include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_bracelets.php"); ?>
<?php include_once("c:/xampp/htdocs/pinkys_pearls/templates/template_navigation.php"); ?>
as
<?php include_once("localhost/pinkys_pearls/templates/template_bracelets.php"); ?>
<?php include_once("localhost/pinkys_pearls/templates/template_navigation.php"); ?>
and make sure with your image paths, if folder varies you cannot get load the images.

How to pass php variable to a new page for deleting a row from the database?

On the list.php page, I am passing a variable using hidden input method in form.
This form redirects to listd.php where the variable is used to run an SQL query to delete a particular row from the database where the variable==name.
If I print the variable on listd.php before processing SQL query then it is visible but during when query is processed it gives unidentified index error.
The code in listd.php works if I take input from the user on the same page.
list.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
<?php
session_start();
if($_SESSION['username'])
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
else
header('location:index.php');
//session_start();
if(isset($_SESSION['username']))
echo "<h3><a href='logout.php'>Logout</a></h3>";
?>
</div>
</div>
</div>
<div class="container">
<h2>Hover Rows</h2>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
-->
<?php
{$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="listd.php" method="post" >';
echo '<input type="hidden" name="del2" value="';?>
<?php echo $row['name'];
echo'"> <input type="submit" value="Delete">';
echo "</td>";
echo "</form>";
}
}
?>
<!--
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
-->
</tbody>
</table>
</div>
</body>
</html>
listd.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> Events </h3>
<div class="row">
<div class="container-fluid text-primary text-center">
<br>
<button class="btn"> Add </button> <br><br>
<button class="btn"> Edit </button> <br><br>
<button class="btn"> Delete </button> <br><br>
<button class="btn"> View </button> <br><br>
</div>
</div>
<?php
session_start();
?>
<form action="listd.php" method="post" class="a">
<table>
<tr>
<td> Category Name </td>
<td>
<strong>
<?php echo $_POST["del2"];
$k=$_POST['del2'];
?>
</strong>
</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" value="Delete" name="delete"> </td>
</tr>
</table>
</form>
<?php
$event=$k;
if(isset($_REQUEST['delete'] )&& $event )
{
$sql="DELETE FROM events WHERE name='$event'";
if(mysqli_query($conn,$sql))
{
echo "deleted Succesfully";
//header('location:listd.php');
}
else
echo "error";
}
?>
</div>
</div>
</div>
</body>
</html>
It's really not necessary to use two forms to do this, unless this is a very dangerous action. this is also the source of your problem. $k is not preserved on the second postback. Requests are stateless. When you submit the second form, the listd.php script runs again from the start, and the values assigned to variables the last time it ran. This is the normal behaviour of HTTP requests in general.
A single-form version might look like this:
list.php
<?php
//this needs to be before anything else otherwise the redirect might fail due to headers already sent.
session_start();
if(isset($_SESSION['username'])) //corrected to use isset(). Only one test for this is needed.
{
echo "<h2>Welcome ".$_SESSION['username']."!</h2>";
echo "<h3><a href='logout.php'>Logout</a></h3>";
}
else
{
header('location:index.php');
die(); //script needs to die because webcrawlers/bots will ignore the redirect header, and view the rest of the page anyway, without permission. Using die() means the rest of the page never gets output.
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sports </title>
<link rel="stylesheet" href="main.css" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Tangerine">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Great+Vibes|Roboto|Barrio" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<?php
require ("config.php");
?>
<div class="row">
<div class="container-fluid">
<div class="jumbotron text-center">
<h3> List Events</h3>
</div>
</div>
</div>
<?php
$message = null; //will hold any extra message to the user resulting from data processing actions (such as delete)
//only run the next section if del2 has been submitted from a postback.
if(isset($_POST['del2']))
{
$event = $_POST['del2'];
$sql= "DELETE FROM events WHERE name='$event'"; //here you should use parameterised queries, I will leave it to you to look this up online, using the link I gave in the comments.
if(mysqli_query($conn,$sql))
{
$message = "Deleted succesfully";
}
else
{
$message = "error";
//here you should check mysqli_error() and log the output somewhere (not visible to the user)
}
}
?>
<div class="container">
<h2>Hover Rows</h2>
<!-- here is an example of how you can inject the confirmation message into somewhere suitable in the page. You can modify this to suit your needs. -->
<?php if ($message != null) { echo "<p><b>".$message."</b></p>"; } ?>
<p>The .table-hover class enables a hover state on table rows:</p>
<table class="table table-hover">
<thead>
<tr>
<th>Event </th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$result="SELECT name FROM events";
$q = mysqli_query($conn,$result) or die(mysqli_error()); //corrected to use mysqli_error not mysql_error
while ($row=mysqli_fetch_array($q))
{
echo "<tr> <td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<button> Add </button> <br><br>';
echo "</td>";
echo "<td>";
echo '<form action="liste.php" method="post" >';
echo '<input type="hidden" name="edit" value="';
echo $row['name'];
echo'"> <input type="submit" value="Edit">';
echo "</form>";
echo "</td>";
echo "<td>";
echo '<form action="list.php" method="post" >';
echo '<input type="hidden" name="del2" value="';
echo $row['name'];
echo'"> <input type="submit" value="Delete" onclick="return confirm("Are you sure?");>'; //adds a confirmation dialog box to the delete button
echo "</td>";
echo "</form>";
}
?>
</tbody>
</table>
</div>
</body>
</html>
You do not need listd.php at all.
P.S. A separate hint: I see you are copying the same HTML <head> etc material into every page script. This is not necessary. You can create two files e.g. header.php and footer.php. In header.php you can put the opening <html> and <head> tags right down to <body> and any other enclosing tags necessary for the consistent layout of all your pages. Then in footer.php you can put the equivalent closing tags. And then in all the other pages of your site you can simply write <?php require_once("header.php"); ?> as the first line and <?php require_once("footer.php"); ?> as the last line. Then any changes you need to make to the headers (e.g. new CSS files or something) are automatically applied to all the pages without tedious copy/paste actions. Although I suggested that you remove your second script here, you can do this for any other pages in your site. It's also a good general principle of code re-use which you can apply to all kinds of situations in your future code.
P.P.S. I'd also consider using an up-to-date doctype. The HTML5 doctype declaration is simply <!DOCTYPE html>. This will likely result in more consistent behaviour of the HTML and CSS in your page, and future-proofs your application against deprecation of older doctypes which are no longer in current use.

I am very new to using PHP. I would like to create a comment box

I am very new to using PHP.I would like to create a comment box for the user.
1. How do you save the comment in the database
2. How do you see if there are any posts
3. How do you display all posts to current page.
I am using Wampsever/MySQL Workbench. May I have help? Thank you!
<?php
require_once("db_connection.php");
require_once("needed_functions.php");
if (isset($_POST['submit']))
{
//Take Comment
$comment_id = $_POST["comment"];
if ($message == "" )
{
$query = "INSERT INTO comment (";
$query .= "comment";
$query .= ") VALUES (";
$query .= " '{$comment}'";
$query .= ")";
//connect &select
$mysqli = new mysqli("localhost", "user_id");
//query
$result = $mysqli->query("INSERT INTO Comment () VALUES();")
//close
$result->close();
}
}
?>
<!DOCTYPE html>
<html>
<title>JAE Movies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<style>
body,h1,h2,h3,h4,h5 {font-family: "Poppins", sans-serif}
body {font-size:16px;}
.w3-half img{margin-bottom:-6px;margin-top:16px;opacity:0.8;cursor:pointer}
.w3-half img:hover{opacity:1}
</style>
<body style= "background-image:url(Roll.jpg)">
<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-black w3-collapse w3-top w3-large w3-padding" style="z-index:3;width:300px;font-weight:bold;" id="mySidebar"><br>
Close Menu
<div class="w3-container">
<h3 class="w3-padding-64"><b>JAE<br>Movies</b></h3>
</div>
<div class="w3-bar-block">
Home
Sign In
Sign Up
Information
Customer Service
Administrator
</div>
</nav>
<!-- Top menu on small screens -->
<header class="w3-container w3-top w3-hide-large w3-light-blue w3-xlarge w3-padding">
?
<span>JAE Movies</span>
</header>
<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!--Start Inserting Page Content-->
<div class="w3-main" style="margin-left:340px;margin-right:40px">
<!-- Header -->
<div class="w3-container" style="margin-top:80px" id="userhome">
<h1 class="w3-jumbo w3-text-white"><b>Lion King</b></h1>
</div>
<!--Image-->
<div class="w3-half">
<img src="Images/LionKing.jpg" alt="LionKing" style="width:100%">
</div>
<!--Description-->
<div class="w3-half">
<p style="color:white";>Lion cub and future king Simba searches for his identity. His eagerness to please others and penchant for testing his boundaries sometimes gets him into trouble.</p></br>
</div>
<!--Buttons-->
<div>
<button type="submit">WATCH TRAILER!</button>
<button type="submit">WATCH MOVIE</button>
</div>
<!--Comments-->
<div>
<br>
<textarea rows="4" cols="50" name="comment" form="usrform">
Enter comment here...</textarea>
<form action=" " method="post" id="com">
<input type ="submit" name="submit" value="submit" class="texty" >
</form>
</div>
When using database connections in PHP make sure you do the following
//connect &select
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
//query
$result = $mysqli->query("INSERT INTO tbl_name () VALUES();") // Add the update comment here
//close
$result->close();
Always remember to :
connect
select
query
close
you'll then need to get all of the comments for the page using the same process but with the select process rather than insert.
<?php
require_once("db_connection.php");
require_once("needed_functions.php");
if(isset($_POST['submit'])){
$comment = mysql_escape_string($_POST['comment']);
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
if($res = $link->query($sql)){
}
else
{
echo "Error".$sql."<br>".$link->error;
}
}
?>
<!DOCTYPE html>
<html>
<title>Movies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<style>
body,h1,h2,h3,h4,h5 {font-family: "Poppins", sans-serif}
body {font-size:16px;}
.w3-half img{margin-bottom:-6px;margin-top:16px;opacity:0.8;cursor:pointer}
.w3-half img:hover{opacity:1}
</style>
<body>
<div class="container">
<img src="images/1.jpg" alt="loinKing" style="width:100%;height:300px;">
<br>
<br>
<form action="" method="post">
<div class="form-group">
<textarea type="text" name="comment" placeholder="Type Comment.." class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="POST" class="btn btn-primary">
</div>
</form>
<!-- Left-aligned -->
<?php
//HERE SHOW OR DISPLAY THE COMMENTS
$q = "SELECT * FROM comments ORDER BY id DESC";
if($r->num_rows > 0){
while($row = $r->fetch_assoc()){
?>
<div class="media">
<div class="media-left">
<img src="images/img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<p>Date Posted : <?php echo $row['date'];?></p>
<p>Comments :<?php echo $row['comment'];?></p>
</div>
</div>
<?php
}
}
else
{
?>
<h4>No Comments Available</h4>
<?php
}
}
else
{
echo "Error".$sql."<br>".$link->error;
}
?>
</div>
</body>
So their is a code which save comment in database , displays in database and if comment is not posted or not available than it show NO COMMENT AVAILABE message.
I'M USING PHP AND MYSQLI HERE. Recommend not to use mysql as it is deprecated.
THE DATABASE TABLE IMAGE
CODE OUTPUT IMAGE
php file:
<?php
$link = new mysqli ('localhost','root','admin','demo1');
if($link->connect_error){
die ("Connection failed".$link->error);
}
if(isset($_POST['submit'])){
$comment = mysql_escape_string($_POST['comment']);
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
if($res = $link->query($sql)){
}
else
{
echo "Error".$sql."<br>".$link->error;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<img src="images/1.jpg" alt="loinKing" style="width:100%;height:300px;">
<br>
<br>
<form action="" method="post">
<div class="form-group">
<textarea type="text" name="comment" placeholder="Type Comment.." class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="POST" class="btn btn-primary">
</div>
</form>
<!-- Left-aligned -->
<?php
//HERE SHOW OR DISPLAY THE COMMENTS
$q = "SELECT * FROM comments ORDER BY id DESC";
if($r = $link->query($q)){
if($r->num_rows > 0){
while($row = $r->fetch_assoc()){
?>
<div class="media">
<div class="media-left">
<img src="images/img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<p>Date Posted : <?php echo $row['date'];?></p>
<p>Comments :<?php echo $row['comment'];?></p>
</div>
</div>
<?php
}
}
else
{
?>
<h4>No Comments Available</h4>
<?php
}
}
else
{
echo "Error".$sql."<br>".$link->error;
}
?>
</div>
</body>
</html>
I hope all of your questions are answered. If not then reply to me....
Error For some reason I'm not finding:
Your screenshot is exactly what I am looking

Issue with foreach loop updating every record, rather than the ones just selected in a checkbox

I have a page with a dropdown box at the top populated from the database, when I select an item from the dropdown it gives a list of results with a checkbox at the end of each line, I want to be able to select, using each checkbox, any number of results, and submit a value back into a field in the database for each result selected.
I sort of have this working, but it submits the value to every field in the database, rather than just the ones selected
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<title>Stock Items</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="css/elegant-icons-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<!-- full calendar css-->
<link href="assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" />
<!-- easy pie chart-->
<link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- owl carousel -->
<link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
<link href="css/jquery-jvectormap-1.2.2.css" rel="stylesheet">
<!-- Custom styles -->
<link rel="stylesheet" href="css/fullcalendar.css">
<link href="css/widgets.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/xcharts.min.css" rel=" stylesheet">
<link href="css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<?php include("navigation.php"); ?>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-lightbulb-o"> </i>Stock</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-lightbulb-o"></i>Stock</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
All Stock
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<div class="col-lg-8">
<select name="search" class="form-control" required >
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `description` FROM `stock_templates`";
$stock_templates = mysql_query($query);
echo "<option value=''>Select Stock Template</option>";
while ($description=mysql_fetch_assoc($stock_templates)) {
echo "<option value='" . $description['id'] . "'>" . $description['description'] . "</option>";
}
?>
</select>
</div>
<div class="col-lg-1">
<input type="submit" name="filter" value="Search" class="btn btn-success" />
</div>
</div>
</form><br><br>
<?php
if(isset($_POST['formSubmit']))
{
$aDoor = $_POST['check_list'];
if(empty($aDoor))
{
echo("<p>You didn't select any items to add to lease.</p>\n");
}
else
{
$N = count($aDoor);
echo("<p>You selected $N item(s) to add to lease: ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
?>
<?php
ob_start( );
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query = mysql_query("UPDATE stock SET lease_id = $lease_id");
$result2 = mysql_query($query);
// check if sent
if ($result2) {
?>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Well done!</strong> Your lease items have been successfully saved.
</div>
<?php
} else {
?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Oh snap!</strong> We could not save your lease items.
</div>
<?php
}
}
}
?>
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
// Extract filter information
$count = 0;
$search = mysql_escape_string(#$_POST['search']);
// select data from the database
$query2 = "SELECT * FROM `stock_templates` ORDER BY `stock_templates`.`id` DESC LIMIT 0";
// Perform Logic
if (array_key_exists("filter", $_POST)) {
// query based on search term
$query2 = "SELECT * FROM `stock` WHERE $search=stocktemplate_id AND lease_id=0";
}
$result2 = mysql_query($query2);
// Result
if (mysql_num_rows($result2) < 1) {
echo "<div align='center'><h2>Please select a stock template above and click search</h2></div>";
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" class="form-horizontal" name="check_list[]">
<div class="form-group">
<label class="control-label col-lg-1" for="lease_id">Lease Number *</label>
<div class="col-lg-10">
<select name="lease_id" class="form-control">
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `leasenumber` FROM `lease`";
$leases = mysql_query($query);
echo "<option value=''>Select Lease..........</option>";
while ($lease=mysql_fetch_assoc($leases)) {
echo "<option value='" . $lease['id'] . "'>" . $lease['leasenumber'] . "</option>";
}
?>
</select>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Item ID</th>
<th>Description</th>
<th>Barcode</th>
<th>Serial</th>
<th>Add To Lease</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result2))
{
$id = $row["id"];
$lease_id = $row["lease_id"];
$barcode = $row["barcode"];
$serial = $row["serial"];
$stocktemplate_id = $row["stocktemplate_id"];
$qa = 0;
?>
<tbody>
<tr>
<td><?php print $id ?></td>
<td><?php $q = mysql_query("SELECT description FROM stock_templates WHERE id = '$stocktemplate_id'"); while ($row = mysql_fetch_array($q)){$qa = $row["description"];} print $qa ?></td>
<td><?php print $barcode ?></td>
<td><?php print $serial ?></td>
<td><input type="checkbox" name="check_list[]" value="<?php print $id ?>" /></td>
<td></td>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<input class="btn btn-danger" type="submit" name="formSubmit" value="Add Selected To Lease" />
</div>
</form>
</section>
</div>
</div>
</section>
</section>
<!--main content end-->
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- jquery ui -->
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<!--custom checkbox & radio-->
<script type="text/javascript" src="js/ga.js"></script>
<!--custom switch-->
<script src="js/bootstrap-switch.js"></script>
<!--custom tagsinput-->
<script src="js/jquery.tagsinput.js"></script>
<!-- colorpicker -->
<!-- bootstrap-wysiwyg -->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<script src="js/bootstrap-wysiwyg-custom.js"></script>
<!-- ck editor -->
<script type="text/javascript" src="assets/ckeditor/ckeditor.js"> </script>
<!-- custom form component script for this page-->
<script src="js/form-component.js"></script>
<!-- custome script for all page -->
<script src="js/scripts.js"></script>
</body>
</html>
No worries. Just put the code of insert query inside foreach() loop. Like this:
foreach($_POST['check_list'] as $item)
{
$sql="INSERT/UPDATE Query";
//for example
$sql = "INSERT INTO table_demo (field_1, TARGET_FIELD, field_2, field_3) VALUES (val_1, $item, val_2, val_3)";
$insert = mysqli_query($connection,$sql);
}
//next code of your choice
That is really Easy to give a go.
See this is same as you want.
In this link the first answer by Sean Valsh is your solution.
Giving the array as name of every checkbox will give you only chacked option's id in array while submitted.
https://stackoverflow.com/a/4997271/6834980
Ask if still have the problem. Happy to help.

Categories