I have already asked a question about PDO user add records to database PDO, now I am unable to select data and insert them into a html form in order to allow a user what to choose and as a consequence to add record into a db table
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
try {
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to database<br />';
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<?php
if ($_GET['action'] == 'edit') {
//retrieve the record's information
$sth = $dbh->prepare = 'SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = ' . $_GET['id'];
$sth = $dbh->execute();
extract($sth = $dbh->fetch());
} else {
//set values to blank
$nome = '';
$cognome = '';
$indirizzo = '';
$civico = 0;
$citta = '';
$prov = '';
}
?>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo ucfirst($_GET['action']); ?> Tages</title>
<style type="text/css">
<!--
#error { background-color: #600; border: 1px solid #FF0; color: #FFF;
text-align: center; margin: 10px; padding: 10px; }
-->
</style>
</head>
<body>
<?php
if (isset($_GET['error']) && $_GET['error'] != '') {
echo '<div id="error">' . $_GET['error'] . '</div>';
}
?>
<form action="commit.php?action=<?php echo $_GET['action']; ?>&type=tages"
method="post" accept-charset="UTF-8">
<table>
<tr>
<td>Nome</td>
<td><input type="text" name="nome" value="<?php echo $nome; ?>"/></td>
</tr><tr>
<td>Cognome</td>
<td><select name="cognome"></td>
<?php
//seleziona il tipo di cognome
$sth = $dbh->prepare = 'SELECT
cognome
FROM
tagesroma';
$sth->execute();
//popola con i risultati
while ($row = $sth->fetch()) {
foreach ($dbh->$row as $value) {
if ($row['id'] == $cognome) {
echo '<option value="' . $row['id'] .
'" selected="selected">';
} else {
echo '<option value="' . $row['id'] . '">';
}
}
}
?>
</select></td>
</tr><tr>
<td colspan="2" style="text-align: center;">
<?php
if ($_GET['action'] == 'edit') {
echo '<input type="hidden" value="' . $_GET['id'] . '" name="id" />';
}
?>
<input type="submit" name="submit"
value="<?php echo ucfirst($_GET['action']); ?>" />
</td>
</tr>
</table>
</form>
</body>
</html>
the error I am dealing with is the following:
Fatal error: Call to a member function execute() on a non-object on line 76
The error Call to a member function execute() on a non-object means this area of the code is invalid:
$sth = $dbh->prepare = 'SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = ' . $_GET['id'];
$sth = $dbh->execute();
The correct way is:
$sth = $dbh->prepare("
SELECT nome, cognome, indirizzo, civico, citta, prov
FROM tagesroma
WHERE id = ?
");
$sth->execute(array($_GET['id']));
Use double-quote if you want to use newlines
Know that prepare() is a function, so following it with = doesn't make sense
Tidy your code for readability
You are not using prepared statements properly. try this:
<?php
$id = $_GET['id'];
$sth = $dbh->prepare("SELECT
nome, cognome, indirizzo, civico, citta,
prov
FROM
tagesroma
WHERE
id = :id");
$sth->bindParam(":id",$id,PDO::PARAM_INT);
$sth->execute();
?>
Related
I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.
I'm using a form to input new projects into my database. One of the fields is Lead Writer. I want to add a drop down menu to that field that will display the names of the lead writers from my database that the user can then select to populate that field. I've managed to get the drop down to appear in the field, but my code isn't generating any names. I tried setting up a function that would call those results, but it's obviously not working. The form worked well prior to my changes, so it's not an issue connecting to the database. Any help would be greatly appreciated.
function query(){
$myNames = "SElECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($result = mysqli_fetch_array($myNames)){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
Lead Writer: <select name="dropdown">
<?php query() ?>
</select>
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
Edited Code:
<html>
<head>
</head>
<body>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
</form>
<?php
$connection->close();
?>
</body>
</html>
2nd Edit:
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($connection){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $connection->query($myNames)) {die($mysqliconnection->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}?>
<?php
$connection->close();
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
</form>
</body>
</html>
You have a variable scope issue - http://php.net/manual/en/language.variables.scope.php. $mysqli is undefined in your function query(). You need to pass it as a param. Also, you were trying to do mysqli_fetch_array() on the query string, instead of the mysqli result. I have updated it to the OO ->fetch_array().
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($record = $result->fetch_array()){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
You will also need to pass it in your call
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
You can add some debugging to find out why it is not printing
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
per your edit - https://stackoverflow.com/posts/34257335/revisions
Your mysqli connection is $connection
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
so not sure why you are trying to use $mysqli
$mysqli->query($myNames)
as $connection != $mysqli.
As you are doing the query in a function, you don't need to rename all instances of $mysqli to $connection, as you can just change to
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
This question already has answers here:
delete row in my database using php pdo [closed]
(2 answers)
Closed 7 years ago.
I want to delete a selected row from my database, but I don´t know how to accomplish it. I am completly new to this topic, so it would be really nice, when you could explain to me.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> PHP F1 - Datenbank</title>
<style>
button {
margin:5px;
margin-left:-0px;
}
.insert {
position:relative;
margin:0px;
margin-bottom:5px;
margin-top:-25px;
}
</style>
</head>
<body>
<h2> Insert Dokument für deine Datensätze ! </h2>
<form action="F1_PHP.php" method="post">
<input type="text" name="jahr" placeholder="Albert-Park"> <br><br>
<input type="text" name="sieger" placeholder="Australien"> <br><br>
<input type="text" name="schnellster" placeholder="Melbourne"> <br><br>
<input type="text" name="strecke" placeholder="Laenge"><br><br>
<input type="submit" name="formdaten" class="insert" value="Insert"> <br>
</form>
<table border="1">
<tr>
<th></th>
<th>Strecke</th>
<th>Land</th>
<th>Stadt</th>
<th>Länge</th>
</tr>
<?php
try {
$server = 'mysql:dbname=f1;host=localhost';
$user = 'root';
$password = '';
$options = array
(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$pdo = new PDO($server, $user, $password, $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($pdo){
if (isset($_POST["formdaten"])) {
$jahr = $_POST["jahr"];
$sieger = $_POST["sieger"];
$schnellster = $_POST["schnellster"];
$strecke = $_POST["strecke"];
$eintrag = $pdo->prepare("INSERT INTO Strecke
(pk_Strecke, Land, Stadt, Laenge) VALUES (?, ?, ?, ?);");
$eintrag->execute(array($jahr, $sieger, $schnellster, $strecke));
if ($eintrag == true) {
echo "Eintrag war erfolgreich";
} else {
echo "Fehler";
}
}
}
}
catch (PDOException $error) {
echo 'Verbindung fehlgeschlagen: ' . $error->getMessage();
}
try {
$query= 'SELECT pk_Strecke, Land, Stadt, Laenge FROM Strecke';
$stmt = $pdo -> query($query);
$deleteString = "";
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Strecke"].'</td>';
echo ' <td>'. $row["Land"]. '</td>';
echo ' <td>'. $row["Stadt"]. '</td>';
echo ' <td>'. $row["Laenge"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
<br>
<input type="submit" name="delete" value="Delete">
<?php
// delete button
?>
<input type="submit" name="update" value="Update">
<?php
//Update button
?>
<br>
<table border="1">
<tr>
<th> </th>
<th> Jahr </th>
<th> Sieger </th>
<th> Schnellste Runde </th>
<th> Strecke </th>
</tr>
<?php
try {
$query= 'SELECT pk_Jahr,Sieger,SchnellsteRunde,pk_fk_Strecke
FROM Rennen join Strecke on pk_fk_Strecke = pk_Strecke
order by pk_Jahr';
$stmt = $pdo -> query($query);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
echo '<tr>';
echo ' <td>'."<input type='radio' name='markiert'>".'</td>';
echo ' <td>'. $row["pk_Jahr"].'</td>';
echo ' <td>'. $row["Sieger"]. '</td>';
echo ' <td>'. $row["SchnellsteRunde"]. '</td>';
echo ' <td>'. $row["pk_fk_Strecke"]. '</td>';
echo '</tr>';
}
echo '</table>';
}
catch (PDOException $error) {
echo 'Fehler beim Lesen der Daten ' . $error->getMessage();
}
?>
</body>
</html>
I appreciate every tip from you.
Use the following statements:
$sql = "DELETE FROM `Rennen` WHERE `pk_Jahr` = :id_to_delete";
$query = $db->prepare( $sql );
$query->execute( array( ":id_to_delete" => 'Value of pk_Jahr of the row to delete' ) );
It looks like you have a good idea of how to set up the PHP side of things, so I'll just deal with the SQL part.
The general syntax for a delete using PDO and MySQL would be as follows:
$query = "DELETE FROM TableName WHERE Field = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
The field you're querying against on that table needs to be unique, unless you're wanting to delete multiple rows (so best to use a primary key for the field and value).
It looks like you're using racing circuits in one of your tables, so your table may look like this (I'll call the table "circuits"):
id (primary key), circuit, country.
You may have the following data in it:
1, Albert Park, Australia
2, Silverstone, Great Britain
3, Adelaide, Australia
To delete Albert Park from the database, you'd run this:
$value = 1;
$query = "DELETE FROM circuits WHERE id = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
To delete all circuits in Australia (2 of the 3 above records):
$value = "Australia;
$query = "DELETE FROM circuits WHERE country = :value";
$stmt = $pdo->prepare($query);
$stmt-> bindParam(':value', $value);
$stmt->execute();
You could pass the value for $value through a form, and using bindParam() protects against SQL injection.
Ok so the problem is very simple, basically when you put for example "W" it should output hotel names and guest's surnames that contain that character. It doesn't that hotel names however it never gives me an output for guest's no matter what I put. There are several matching for guest's that should appear however I get nothing. I can't see any mistakes with my code... Help.
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = strip_tags( trim( $_POST['search'] ) );
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
$stmt = $conn->prepare("SELECT * FROM `hotel` h
INNER JOIN `booking` b ON h.`hotel_id`=b.`hotel_id`
INNER JOIN `guest` g ON g.`guest_id`=b.`guest_id`
WHERE `name` LIKE :search_term;");
$stmt->bindValue(':search_term','%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Hotels Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['name']."'>".$hotel['name']."</a></td>
</tr>";
}
echo "</table>";
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN hotel ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term;");
$stmt->bindValue(':search_term', '%' . $search_term . '%');
$stmt->execute();
echo "
<table>
<tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['first_name']."'>".$hotel['last_name']."</a></td>
</tr>";
}
echo "</table>";
$conn = NULL;
}
?>
</body>
</html>
With PDO Prepared statements with LIKE prepare FULL literal first.See PDO Wiki
ie.
$name = "%$name%";
I have simplified your code using one query. I have tested it on 2 tables, you will need to JOIN other table
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
$host= "localhost";
$username="XXXX";
$password="XXXX";
$database="XXXX";
function writeTable($host,$database, $username, $password,$search_term) {
//Create query
$sql = "SELECT hotel.name AS hotel, guest.name AS guest
FROM `hotel`
LEFT JOIN `guest` ON hotel.guest = guest.id
WHERE hotel.name LIKE ?
OR guest.name LIKE ?
";
$html = '<table cellpadding="1" cellspacing="1">'. "\n";
//array for column names
$columnNames = array("hotel","guest");
//table header
$html .= '<tr>';
foreach ($columnNames as $value){
$html .= '<th>' . $value . '</th>';
}
$html .= '</tr>'. "\n";
// connect to the database
$db = new PDO("mysql:host=$host;dbname=$database", $hotelname, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Prepare and execute query
$stmt = $db->prepare($sql);
$stmt->execute(array($search_term,$search_term));
// setting the fetch mode
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//Add content
while($row = $stmt->fetch()) {
$html .= '<tr>';
$html .= '<td>' . $row['hotel'] . '</td>';
$html .= '<td>' . $row['guest'] . '</td>';
$html .= '</tr>'. "\n";
}
$html .= '</table>';
echo $html;
// close the connection
$dbh = null;
}
$search = strip_tags(trim($_POST['search'] ) );
if(isset($search) ){
if ($search != ''){
$search_term = '%'.$search.'%';
}else{
$search_term ='';
}
}
writeTable($host,$database, $hotelname, $password,$search_term);
?>
You should be able to modify to suit.
This is my database of table cart when I add product to my cart table then error occurs
Database
mysql_query($query, $db) or die(mysql_error($db));
$query = 'CREATE TABLE IF NOT EXISTS ecomm_temp_cart (
session CHAR(50) NOT NULL,
product_code CHAR(5) NOT NULL,
qty INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (session, product_code),
FOREIGN KEY (product_code) REFERENCES ecomm_products(product_code)
)
ENGINE=MyISAM';
my product table
mysql_query($query, $db) or die(mysql_error($db));
$query = 'CREATE TABLE IF NOT EXISTS ecomm_products (
product_code CHAR(5) NOT NULL,
name VARCHAR(100) NOT NULL,
description MEDIUMTEXT,
price DEC(6,2) NOT NULL,
PRIMARY KEY(product_code)
)
ENGINE=MyISAM';
<?php
session_start();
require 'db.inc.php';//connection to database
?>
<html>
<head>
<title>Here is Your Shopping Cart!</title>
<style type="text/css">
th { background-color: #999;}
td { vertical-align: top; }
.odd_row { background-color: #EEE; }
.even_row { background-color: #FFF; }
</style>
</head>
<body>
<h1>Comic Book Appreciation Store</h1>
<?php
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$session = session_id();
$query = 'SELECT
t.product_code, qty,
name, description, price
FROM
ecomm_temp_cart t JOIN ecomm_products p ON
t.product_code = p.product_code
WHERE
session = "' . $session . '"
ORDER BY
t.product_code ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));
$rows = mysql_num_rows($result);
if ($rows == 1)
{
echo '<p>You currently have 1 product in your cart.</p>';
}
else
{
echo '<p>You currently have ' . $rows . ' products in your cart.</p>';
}
if ($rows > 0)
{
?>
<table style="width: 75%;">
<tr>
<th style="width: 100px;"></th><th> Item Name </th><th> Quantity </th>
<th> Price Each </th><th> Extended Price </th>
</tr>
<?php
$total = 0;
$odd = true;
while ($row = mysql_fetch_array($result))
{
echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
$odd = !$odd;
extract($row);
?>
<td style="text-align:center;"><a href="ecomm_view_product.php?product_code=<?php
echo $product_code; ?>"><img src="images/<?php echo $product_code;
?>_t.jpg"
alt="<?php echo $name; ?>"/></a></td>
<td><a href="ecomm_view_product.php?product_code=<?php echo $product_code;
?>"><?php
echo $name; ?></a></td>
<td>
<form method="post" action="ecomm_update_cart.php">
<div>
<input type="text" name="qty" maxlength="2" size="2"
value="<?php echo $qty; ?>"/>
<input type="hidden" name="product_code"
value="<?php echo $product_code; ?>"/>
<input type="hidden" name="redirect" value="ecomm_view_cart.php"/>
<input type="submit" name="submit" value="Change Qty"/>
</div>
</form>
</td>
<td style="text-align: right;"> $<?php echo $price; ?></td>
<td style="text-align: right;"> $<?php echo number_format
($price * $qty, 2); ?>
</td>
</tr>
<?php
$total = $total + $price * $qty;
}
?>
</table>
<p> Your total before shipping is:
<strong>$<?php echo number_format($total, 2); ?></strong></p>
<form method="post" action="ecomm_checkout.php">
<div>
<input type="submit" name="submit" value="Proceed to Checkout" style="font- weight: bold;"/>
</div>
</form>
<form method="post" action="ecomm_update_cart.php">
<div>
<input type="hidden" name="redirect" value="ecomm_shop.php"/>
<input type="submit" name="submit" value="Empty Cart"/>
</div>
</form>
<?php
}
?>
<hr/>
<p><< Back to main page </p>
</body>
</html>
I have created a product web page and when I add quantity and click on add to cart then it shows duplicate error . I try to fix it but can't fix it..
> My update cart
<?php
require 'db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
session_start();
$session = session_id();
$qty = (isset($_POST['qty']) && ctype_digit($_POST['qty'])) ? $_POST['qty'] : 0;
$product_code = (isset($_POST['product_code'])) ? $_POST['product_code'] : '';
$action = (isset($_POST['submit'])) ? $_POST['submit'] : '';
$redirect = (isset($_POST['redirect'])) ? $_POST['redirect'] : 'ecomm_shop.php';
switch ($action)
{
case 'Add to Cart':
if (!empty($product_code) && $qty > 0) {
$query = 'INSERT INTO ecomm_temp_cart(session, product_code, qty)
VALUES
("' . $session . '", "' .
mysql_real_escape_string($product_code, $db) . '", ' . $qty . ')';
mysql_query($query, $db) or die(mysql_error($db));
}
header('Location: ' . $redirect);
exit();
break;
case 'Change Qty':
if (!empty($product_code)) {
if ($qty > 0) {
$query = 'UPDATE ecomm_temp_cart
SET
qty = ' . $qty . '
WHERE
session = "' . $session . '" AND
product_code = "' .
mysql_real_escape_string($product_code, $db) . '"';
} else {
$query = 'DELETE FROM ecomm_temp_cart
WHERE
session = "' . $session . '" AND
product_code = "' .
mysql_real_escape_string($product_code, $db) . '"';
}
mysql_query($query, $db) or die(mysql_error($db));
}
header('Location: ' . $redirect);
exit();
break;
case 'Empty Cart':
$query = 'DELETE FROM ecomm_temp_cart
WHERE
session = "' . $session . '"';
mysql_query($query, $db) or die(mysql_error($db));
header('Location: ' . $redirect);
exit();
break;
}
?>
Your answer is signifying you already have that primary key in the table.
The primary key of the table ecomm_temp_cart is (session, product_code). So you already have a row with that session and product_code.
If you are trying to update the quantity, you should be using REPLACE instead of INSERT or simply an UPDATE statement. REPLACE can be a drop in replacement for INSERT and will delete the existing row and insert the new row, effectively overwriting it.
Another possibility is you are not using a valid product_code. From your error, the product_code is 0000. If that isn't correct, then you're probably using the default product_code for each insert.