Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.
Related
I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.
This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];
i have here my codes regarding my checkboxes, but i got some errors when i click my submit button. though it prints all the values i selected on the checkbox but ive got an error on my sql script saying "Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\project\candidate\president2.php on line 21". i just want to save the values i selected on my database. pls help..
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
//this is my line 21 error. what i want here is to save the selected checkbox into my database but i got some error and i couldnt save it to my database
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].value = true)
{
return document.getElementById('txt').innerHTML =document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->studid ."' value='" . $row->fname . " ". $row->mname ." ". $row->lname . "'onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
</body>
</html>
heres the preview of my output, first pic is i selected 2 candidate and the other is one.
The mysqli_query function requires the $mysqli link to be the first parameter. There are two ways you can fix your error. Below is the ERROR
mysqli_query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
To fix this simply change it to one of the two below > (Id use the first option because you already use it in your code somewhere.)
$mysqli->query("INSERT INTO sample (name) VALUES ('". $ch ."') ");
OR
mysqli_query($mysqli, "INSERT INTO sample (name) VALUES ('". $ch ."') ");
As it says, the function mysqli_query() expects at least two parameters. According to the PHP documentation, the first parameter should be:
A link identifier returned by mysqli_connect() or mysqli_init()
Followed by the query as the second parameter. You don't appear to be using either of those functions in your code. Seeing that you declared a mysqli object, you probably meant to use $mysqli->query() instead.
Just take a look at my example and i'm hoping that it would helps you..:-
<?php
if(isset($_POST['team']))
{
foreach($_POST['team'] as $value){
$insert=mysql_query("INSERT INTO team('team') VALUES ('$value')");
}
}
?>
<html>
<body>
<form method="post" action="lol.php">
<input type="checkbox" name="team[]" value="IN"> India<br />
<input type="checkbox" name="team[]" value="DK"> Dark <br />
<input type="checkbox" name="team[]" value="LA"> lolax <br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
I have two php pages and I'd like to check which button is
checked in the fist one so be able to use its value in the next php
page.The problem is that the submit button is into a while loop so I
can't use different values, may it can be using an i variable but I
don't know how. form of the first page is:
<form name="myForm" action="admin.php" method="post">
<table BORDER=1....... > <?php $link = mysql_connect('localhost', 'root', ''); if
(!$link) {
die('Could not connect: ' . mysql_error()); }
mysql_select_db("nowdeal");
$query = mysql_query("SELECT * FROM application ORDER BY date");
WHILE($rows = mysql_fetch_array($query)):
$date = $rows['date'];
$username = $rows['username'];
$advers = $rows['advers'];
$id = $rows['id'];
echo '<tr>';
echo "$date";
echo "</br>";
echo "$username";
echo "</br>";
echo "$advers";
echo "</br>";
echo "$address";
echo "</td>";
echo '<td align="left">';
echo '<input type="submit" name="action" value="edit" />';
$_SESSION["id"]=$id;
echo '</td>';
echo '</tr>';
endwhile; ?> </table> </form>
in the next page, php code is like:
<?php session_start();
$con = mysql_connect("localhost","root",""); if (!$con) {
die('Could not connect: ' . mysql_error()); }
mysql_select_db("nowdeal", $con);
mysql_query("SET names 'utf8'");
if(isset($_POST['paid']))
{ if($_POST['paid']=="yes") ///is a value from a drop down list
{mysql_query("UPDATE application SET paid='yes' WHERE .....");}
///i want to be like : WHERE id=session[id], but when it works it
takes only //the last id ,so be upadated the last row only
?>
If you want to pass a value over to your new form, insert the value into a hidden form element:
echo '<input type="hidden" name="sessionId" value="' . $id . '"/>';
So that in your next page, you can access this value using:
$_POST['sessionId'];
P.S. You really need to change the way you're accessing your data. Access the data first, preferably using an external class, and then use the data in your rendered output. Don't mix HTML and PHP data logic as if they're best buds.
I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)