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.
Related
My code is not appropriately editing or deleting my comments. I put my code through a syntax checker and that doesn't seem to be the problem. I have tried going through all the articles I could find and even tried multiple different methods but nothing seems to be working.
The issue is that I keep getting this error
Notice: Undefined index: id in C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php on line 5
and when I click on edit the boxes will be filled with text like
Title:
<br /><b>Notice</b>: Trying to access array offset on value of type null in <b>C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php</b> on line <b>20</b><br />
and Comment:
<br /><b>Notice</b>: Trying to access array offset on value of type null in <b>C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php</b> on line <b>24</b><br />
I have tried multiple different ways to define id but to no avail. I have looked and implemented all the solutions I could find on StackOverflow but with no luck.
This is what I used to create the comments table:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`page_id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL DEFAULT '-1',
`name` varchar(255) NOT NULL,
`content` text NOT NULL,
`submit_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
This is my code:
//This is the comments.php:
<?php
// Update the details below with your MySQL details
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'database_name';
try {
$pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error
exit('Failed to connect to database!');
}
// Below function will convert datetime to time elapsed string
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array('y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second');
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
// This function will populate the comments and comments replies using a loop
function show_comments($comments, $parent_id = -1) {
$html = '';
if ($parent_id != -1) {
// If the comments are replies sort them by the "submit_date" column
array_multisort(array_column($comments, 'submit_date'), SORT_ASC, $comments);
}
// Iterate the comments using the foreach loop
foreach ($comments as $comment) {
if ($comment['parent_id'] == $parent_id) {
// Add the comment to the $html variable
$html .= '
<div class="comment">
<div>
<h3 class="name">' . htmlspecialchars($comment['name'], ENT_QUOTES) . '</h3>
<span class="date">' . time_elapsed_string($comment['submit_date']) . '</span>
</div>
<p class="content">' . nl2br(htmlspecialchars($comment['content'], ENT_QUOTES)) . '</p>
<a class="reply_comment_btn" href="#" data-comment-id="' . $comment['id'] . '">Reply</a>
<a href=edit.php>edit</a>
<a href=delete_confirm.php>delete</a>
' . show_write_comment_form($comment['id']) . '
<div class="replies">
' . show_comments($comments, $comment['id']) . '
</div>
</div>
';
}
}
return $html;
}
// This function is the template for the write comment form
function show_write_comment_form($parent_id = -1) {
$html = '
<div class="write_comment" data-comment-id="' . $parent_id . '">
<form>
<input name="parent_id" type="hidden" value="' . $parent_id . '">
<input name="name" type="text" placeholder="Your Name" required>
<textarea name="content" placeholder="Write your comment here..." required></textarea>
<button type="submit">Submit Comment</button>
</form>
</div>
';
return $html;
}
// Page ID needs to exist, this is used to determine which comments are for which page
if (isset($_GET['page_id'])) {
// Check if the submitted form variables exist
if (isset($_POST['name'], $_POST['content'])) {
// POST variables exist, insert a new comment into the MySQL comments table (user submitted form)
$stmt = $pdo->prepare('INSERT INTO comments (page_id, parent_id, name, content, submit_date) VALUES (?,?,?,?,?)');
$stmt->execute([ $_GET['page_id'], $_POST['parent_id'], $_POST['name'], $_POST['content'], date('Y-m-d H:i:s') ]);
exit('Your comment has been submitted! Please reload the page to view your comment.');
}
// Get all comments by the Page ID ordered by the submit date
$stmt = $pdo->prepare('SELECT * FROM comments WHERE page_id = ? ORDER BY submit_date DESC');
$stmt->execute([ $_GET['page_id'] ]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the total number of comments
$stmt = $pdo->prepare('SELECT COUNT(*) AS total_comments FROM comments WHERE page_id = ?');
$stmt->execute([ $_GET['page_id'] ]);
$comments_info = $stmt->fetch(PDO::FETCH_ASSOC);}
else {
exit('No page ID specified!');
}
?>
<div class="comment_header">
<span class="total"><?=$comments_info['total_comments']?> comments</span>
Write Comment
</div>
<?php
if($_SESSION['is_open'] = TRUE){
echo show_write_comment_form();
}else{
echo "Please login to post.";
echo "</br>";
}
if($_SESSION['is_open'] = TRUE){
echo show_comments($comments);
}else{
echo "Please login to see others comments.";
}
?>
//This is the edit.php:
<?php
// connect to SQL
require_once('includes/mysqli_connect.php');
#data preparation for the query
$id = intval($_GET["id"]);
# selects title and description fields from database
$sql = "SELECT * FROM comments WHERE id= '$'";
$result = mysqli_query($dbc,$sql) or die(mysqli_connect_error());
# retrieved by using $row['col_name']
$row = mysqli_fetch_array($result);
?>
<h3>Edit</h3>
<form action=<?="save_edit.php?id='$id'"?>enctype="multipart/form-data" method="post" name="myForm" >
<table>
<tr>
<td><b>Title</b></td>
<td><input type="text" size="70" maxlength="100" name="name" value="<?php $row['name'] ?>"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><textarea cols="80" rows="18" name="content"><?php $row['content']; ?></textarea></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
//This is the save_edit.php:
<?php
require_once('includes/mysqli_connect.php');
#data preparation for the query
$id = intval($_POST["id"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysqli_real_escape_string($value);
$sql = "UPDATE comments SET
name='$_POST[name]',
content='$_POST[content]',
WHERE id=$id";
if (mysqli_error()) {
die('Error: ' . mysqli_error());
}
mysqli_close($dbc);
header ("location: index.html");
?>
//This is the delete.php:
<?php
require_once('includes/mysqli_connect.php');
$id = $_GET['comments_id'];
if($_SESSION['is_open'] = TRUE) {
session_start();
echo "Welcome | " . $_SESSION['user_name'] . "!";
$query = "DELETE FROM comments WHERE id=$id";
$result = mysqli_query($dbc, $query);
if($result){
echo "<br>The selected comment has been deleted.";
} else{
echo"<br>The selected comment could not be deleted.";
}
}else {
echo "login please";
header("Location: login.php");
}
echo "<p><a href=index.html>Go back to the main page</a></p>";
mysqli_close($dbc);
?>
If you are wondering about the is_open that is how I confirm that the user is logged in before allowing them to access the forum.
In your "save_edit.php" file you are not doing anything with the SQL query. With mysqli should look something like this: $dbc->query($sql)
I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...
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();
?>
Hi there I have many implementations of some php files. All of which have some errors. I will start off with an apology as this is my first question on here and I am certain that I will do this incorrectly as I see many first timers do. I will give as much info as possible and make it relevant to as many people as possible.
I have a database and am having trouble deleting from it. The database is simple. It includes resource_id name room description time_available and uer_id.
Although I expect it to output name description and resources_id it only outputs name and description and it will not let me delete name by resources_id.
How to delete from my database in PHP/mysql?
This is my delete_resources.php
{
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>
<?php
$db_host = "#######";
// Place the username for the MySQL database here
$db_username = "#######";
// Place the password for the MySQL database here
$db_pass = "#######";
// Place the name for the MySQL database here
$db_name = "#######";
//
$con = mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$result = mysqli_query($con, "SELECT * FROM resources");
echo 'name' . "\t" . 'description' . "\t" . 'resources_id';
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . "\t" . $row['description'] . "\t" . $row['resources_id'];
echo "<br>";
}
// Echoes: string
echo gettype($array);
//
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Resource ID</td>
<td><input name="resources_id" type="text" id="resources_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
//
}
You are not executing that delete query. Should look like
$recources_id=intval($resources_id);
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); // This is missing
$sql_query="Delete from your_table_name where id ='".$your_id."'";
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
Your $result is not relevant at all with your delete query (it is referring to the $result above, not the one with the delete). Try changing to this and see if it works.
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); //add this line
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}
here I'm trying to display the record of a member and trying to edit the details.
First, I'm fetching the details from a database into textboxes, then, when I should hit the submit button..it should update the entry which is updated and should keep the original value of the textbox which is not updated.
Here's the code :-
The first one is of editmember.php
<?php
session_start();
include 'dbconnector.php';
$receivedusername=$_REQUEST['username'];
$parentusername=$_SESSION['username'];
$_SESSION['cusername']=$receivedusername;
//check session
if((isset($_SESSION['logged'])) && ($_SESSION['logged']==1))
{
//now map the user to it's parent account
$query="select * from master_member where parentusername = '" . $parentusername . "' and currentusername = '" . $receivedusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$row=mysql_fetch_assoc($result);
//account mapped, green signal to proceed
?>
<form action="memberaction.php?action=edit" method="post">
<table>
<tr>
<td>Username : <input type="text" name="usrnm" value="<?php echo ($row['currentusername']); ?>" /></td>
</tr>
<tr>
<td>Email : <input type="text" name="eml" value="<?php echo ($row['currentemail']); ?>" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
<?php
}
else
{
echo "You aren't authorized to perform this task, redirecting.";
header('refresh:2;URL=members.php');
exit();
}
}
else
{
header('Location:login.php');
exit();
}
?>
memberaction.php
case 'update':
$memberusername=$_SESSION['cusername'];//username of the member, whose account is to be edited.
$parentusername=$_SESSION['username'];//username of the parent.
//since the account is already matched to the parent account before, we do not need to do it again.
//get the field value
$usrnm=(isset($_POST['usrnm'])) ? $_POST['usrnm'] : '';
$eml=(isset($_POST['eml'])) ? $_POST['eml'] : '';
$query="update master_member set currentusername = '" . $usrnm . "' and currentemail = '" . $eml . "' where parentusername = '" . $parentusername . "' and currentusername = '" . $memberusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if($result)
{
echo "updated";
header('refresh:2;URL=members.php');
exit();
}
else
{
echo "Errors";
}
break;
After I hit the submit button, it displays successfully updated, but no change takes place at the database.
What possible mistake I'm doing ?
My DB structure is like :-
http://sqlfiddle.com/#!2/969c54/2