I have a problem when I fetching data from database and row it I Got an error.
How To fetch data From database using while and row it.
Fatal error: Call to a member function fetch() on a non-object in
Thanks in advance..
Here is my Code..
<body>
<?php
$id = $_GET['id'];
$iqry = $mysqli->prepare("SELECT itemcode,itemname,brandname,quantity FROM table_inventory WHERE id = ?");
$iqry->bind_param('i', $id);
$iqry->execute();
$iqry->bind_result($itemcode,$itemname,$brandname,$quantity);
$res = $iqry->store_result();
while ($row = $res->fetch()){
$itemcode = $row['itemcode'];
$itemname = $row['itemname'];
$brandname = $row['brandname'];
$quantity = $row['quantity'];
}
?>
<form method="post" name="increasing" action="save.php">
<table>
<tr><td>Itemcode</td><td>:</td><td><input type="text" name="itemcode" required="required" value="<?php echo $itemcode; ?>">/></td></tr>
<tr><td>Itemname</td><td>:</td><td><input type="text" name="itemname" required="required" value="<?php echo $itemname; ?>"/></td></tr>
<tr><td>Brandname</td><td>:</td><td><input type="text" name="brandname" required="required" value="<?php echo $brandname; ?>"/></td></tr>
<tr><td>Quantity</td><td>:</td><td><input type="text" name="quantity" required="required" value="<?php echo $quantity; ?>"/></td></tr>
<tr><td></td><td></td><td><input type="submit" class="myButton" value="Save"/></td></tr>
</table>
</form>
<body>
You seem to be mixing up mysqli_stmt and mysqli_result methods.
Try making the following changes:
LIMIT your resultset to one
... FROM table_inventory WHERE id = ? LIMIT 1
Stick with the mysqli_stmt as you seem to be further along with that
$iqry->bind_param('i', $id);
$iqry->execute();
$iqry->bind_result($itemcode, $itemname, $brandname, $quantity);
if (!$iqry->fetch()) {
throw new Exception('No results found for ID ' . $id, 404);
}
// You can now use $itemcode, $itemname, $brandname and $quantity,
// they will all be set
?>
<form ...
Related
Two tables Order and Line_items are Relate with each other as order_id is placed in line items,
now first populate the order table and then lineitems table on the base of order table's id.
All of the heppening in one isset() has two functions one add values in orders table and second function take order id and then populate the lineitems function.
Problems is for the very first lineitems the order id is "" in Html form's value attribute of order_id. (very hard for me to explain this problem).
Here is my Php isset() function.
if(isset($_POST['check_out'])){
$user_id = $_POST['user_id'];
$shipping_address = $_POST['shipping_address'];
$billing_address = $_POST['billing_address'];
$shipping_method_id = $_POST['shipping_method_id'];
$grand_total = $_POST['grand_total'];
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
$order_id = $_POST['latestorder'];
$product_id = $_POST['product_id'];
$product_price = $_POST['product_price'];
$product_quantity = $_POST['product_quantity'];
$product_total = $_POST['product_total'];
if (empty($order_id)) {
$order_id=$order->latestOrderRecord();
$order_id=+1;
}
$id= count($product_id);
for ($i=0; $i <$id ; $i++) {
$line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]);
// $shoping_cart->
header('location:../cart.php');
}
}
html form
<form method="post" action="n/GetPostData.php" class="woocommerce-shipping-calculator">
<td data-title="Shipping">
Flat Rate:
<span class="amount">$300.00</span>
<p><a data-toggle="collapse" aria-controls="calculator" href="#calculator" aria-expanded="false" class="shipping-calculator-button">Calculate Shipping</a></p>
<div id="calculator" class="shipping-calculator-form collapse">
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<select rel="calc_shipping_state" class="country_to_state" id="calc_shipping_country" name="shipping_method_id">
<option>Select Shipment Method</option>
<?php $shipping_method=$shipment_method->allShipmentMethod();
while ($row=mysqli_fetch_assoc($shipping_method)) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>
</p>
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<input type="text" id="calc_shipping_postcode" name="shipping_address" placeholder="Shipping Address" class="input-text">
</p>
<p id="calc_shipping_state_field" class="form-row form-row-wide validate-required">
<input type="text" id="calc_shipping_postcode" name="billing_address" placeholder="Billing Address" class="input-text">
</p>
</div>
</td>
</tr>
<tr class="order-total">
<th>Total</th>
<td data-title="Total">
<strong><span class="amount">$<?php echo $total; ?></span></strong>
<input type="hidden" name="grand_total" value="<?php echo $total ?>">
<input type="hidden" name="user_id" value="<?php echo $id ?>">
<?php $latestrecord=$order->latestOrderRecord(); ?>
<input type="hidden" name="latestorder" value="<?php echo $latestrecord ?>">
<?php $total=0; $all_cart_products=$shoping_cart->allShopingcartValue($id);
while ($row=mysqli_fetch_assoc($all_cart_products)) { ?>
<input type="hidden" name="product_id[]" value="<?php echo $row['product_id']; ?>">
<input type="hidden" name="product_quantity[]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="product_price[]" value="<?php echo $row['price']; ?>">
<input type="hidden" name="product_total[]" value="<?php echo $row['total']; ?>">
<?php } ?>
<p><button type="submit" class="button" name="check_out" type="submit">Chcek Out</button></p>
</td>
</tr>
</form>
for the very first time when order table is empty the name="latestorder" show "" (no value).
Here is latestOrderRecord() function definition
public function latestOrderRecord()
{
$query="SELECT MAX(id) AS LatestRecord FROM orders";
$conn=$this->Connection();
$result = mysqli_query($conn,$query);
$num_rows = mysqli_num_rows($result);
if ($num_rows>0) {
while ($row=mysqli_fetch_assoc($result)) {
$latestrecord=$row['LatestRecord'];
}
}
return $latestrecord;
}
Issue is that, you are using header() redirection inside your for() loop:
for ($i=0; $i <$id ; $i++) {
header('location:../cart.php'); // that is the issue
}
You must need to use a variable for success in for loop, then you can use it outside the loop for redirection, something like:
HINT:
if($success){
header('location:../cart.php');
exit(); // always use exit() after header() otherwise script execution will not stop
}
Edit:
As per your comment, you are getting order id 0 in lineitem table, because you are inserting $_POST['latestorder'] value which is 0 because you dont have latest ID.
you need to insert the last inserted id of this query:
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
return last inserted id from addOrder() method, and store it into a new variable and use this variable in your lineitem table something like:
$lastInsertID = $order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
and, here $line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]); replace $order_id with $lastInsertID
Make sure, method addOrder() returns last inserted ID.
I have set a custom function to update my query however it doesn't seem to read the variables i am not sure where i am going wrong.
This is my function.
function update_product($productID, $productName, $productDescription, $productPrice, $categoryID){
global $conn;
$sql = "UPDATE product SET productName = :productName, productDescription = :productDescription, productPrice = :productPrice, categoryID = :categoryID WHERE productID = :productID";
$statement = $conn->prepare($sql);
$statement->bindValue(':productName', $productName);
$statement->bindValue(':productDescription', $productDescription);
$statement->bindValue(':productPrice', $productPrice);
$statement->bindValue(':categoryID', $categoryID);
$statement->bindValue(':productID', $productID);
$result = $statement->execute();
$statement->closeCursor();
return $result;
}
This is where i am calling the function
$result = update_product($productID, $productName, $productDescription, $productPrice, $categoryID);
I will also add my function where i am getting the ID and loading the inputs...
function select_productspreparedGETID(){
global $conn;
$productID = $_GET['id'];
//prepared
$sql = "SELECT * FROM product WHERE productID = :productID";
$statement = $conn->prepare($sql);
$statement->bindValue(':productID', $productID);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor();
foreach($result as $row):
?>
<form method="post" action="../controller/product_update_process.php" enctype="multipart/form-data">
<div>
<label>Name* </label>
<input id="Product_Name" type="text" name="Product_Name" value="<?php echo $row['productName'] ?>" />
</div>
<div>
<label>Description* </label>
<textarea id="productDescription" name="productDescription" /><?php echo $row['productDescription'] ?></textarea>
</div>
<div>
<label>Price* </label>
<input id="Price" type="text" name="Price" value="<?php echo $row['productPrice'] ?>" />
</div>
<input type="submit" name="submit" value= "Update Cart">
</form>
<?php
endforeach;
}
Any advice on how to improve my structure or better yet beat this error would be seriously appreciated i have been stuck for the last 20hours.
You are defining $productID = $_GET['id']; inside a function and using the same variable in another function. The $productID is clearly not available to other functions. Make sure that it is defined outside any functions.
Currently the variable is only available to the local scope in which it is defined. For example, define $productID outside any functions:
$productID = $_GET['id'];
You can send this variable to select_productspreparedGETID() as an argument:
function select_productspreparedGETID($productID){
//Your code
}
And then you have $productID inside both functions update_product() and select_productspreparedGETID() because update_product() already has $productID as an argument.
While editing a specific record using PHP code given below, all records in the database are edited simultaneously to the some garbage values. Here "db" is the Database. I am new to PHP and SQL. Please help
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks, $isdate, $issuedto, $returndate)
{
?>
<!DOCTYPE HTML PUBLIC >
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<form action="edit.php" method="post">
<div>
<p><strong>Report No.:</strong> <?php echo $reportno; ?></p>
<strong>Date of receipt: *</strong> <input type="date" name="dateofreceipt" value="<?php echo $dateofreceipt; ?>"/><br/>
<strong>Report Title: *</strong> <input type="text" name="title" value="<?php echo $title; ?>"/><br/>
<strong>Report Type: *</strong> <input type="text" name="type" value="<?php echo $type; ?>"/><br/>
<strong>Issuing agency: *</strong> <input type="text" name="issuingagency" value="<?php echo $issuingagency; ?>"/><br/>
<strong>Marked to: *</strong> <input type="text" name="markedto" value="<?php echo $markedto; ?>"/><br/>
<strong>Date: *</strong> <input type="date" name="date" value="<?php echo $date; ?>"/><br/>
<strong>Remarks: *</strong> <input type="text" name="remarks" value="<?php echo $remarks; ?>"/><br/>
<strong>Issuing Date: *</strong> <input type="date" name="isdate" value="<?php echo $isdate; ?>"/><br/>
<strong>Issued To: *</strong> <input type="text" name="issuedto" value="<?php echo $issuedto; ?>"/><br/>
<strong>Return Date: *</strong> <input type="date" name="returndate" value="<?php echo $returndate; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$reportno = $_POST['reportno'];
$dateofreceipt = mysql_real_escape_string(htmlspecialchars($_POST['dateofreceipt']));
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$issuingagency = mysql_real_escape_string(htmlspecialchars($_POST['issuingagency']));
$markedto = mysql_real_escape_string(htmlspecialchars($_POST['markedto']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
$isdate = mysql_real_escape_string(htmlspecialchars($_POST['isdate']));
$issuedto = mysql_real_escape_string(htmlspecialchars($_POST['issuedto']));
$returndate = mysql_real_escape_string(htmlspecialchars($_POST['returndate']));
//renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date,$remarks, $isdate, $issuedto, $returndate, $error);
// save the data to the database
mysql_query("UPDATE `db` SET `Report No.`='[$reportno]',`Date of receipt`='[$dateofreceipt]',`Report Title`='[$title]',`Report Type`='[$type]',`Issuing agency`='[$issuingagency]',`Marked to`='[$markedto]',`Date`='[$date]',`Remarks`='[$remarks]',`Issuing date`='[$isdate]',`Issued to`='[$issuedto]',`Return Date`='[$returndate]' WHERE `Report No.`= '$id'")
// once saved, redirect back to the view page
header("Location: view.php");
}
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM db WHERE `Report No.`= '$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$reportno = $row['Report No.'];
$dateofreceipt = $row['Date of receipt'];
$title= $row['Report Title'];
$type= $row['Report Type'];
$issuingagency= $row['Issuing agency'];
$markedto= $row['Marked to'];
$date= $row['Date'];
$remarks=$row['Remarks'];
$isdate= $row['Issuing date'];
$issuedto= $row['Issued to'];
$returndate= $row['Return Date'];
// show form
renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks ,$isdate, $issuedto, $returndate, '');
}
?>
Try this query for updation. Also dont forget to add semicolons after statements. Use mysqli_* Functions instead of mysql_*
mysqli_query("UPDATE `db` SET `Date of receipt`='$dateofreceipt',`Report Title`='$title',`Report Type`='$type',`Issuing agency`='$issuingagency',`Marked to`='$markedto',`Date`='$date',`Remarks`='$remarks',`Issuing date`='$isdate',`Issued to`='$issuedto',`Return Date`='$returndate' WHERE Report No = $reportno");
Several issues here:
The mysql api in PhP is deprecated. Don't bet on it working for longer. Use the mysqli api instead.
In your query the "where 1 part is completly superflous. 1 means true and where 1 means all records, at which point you can leave the WHERE out completly. You probably wanted to use WHERE somekey = 1, which is different.
try this
mysql_query("UPDATE db SET Report No.=".'$reportno'.",Date of receipt=."'$dateofreceipt'.",Report Title=."'$title'.",Report Type=."'$type'.",Issuing agency=."'$issuingagency'.",Marked to=."'$markedto'.",Date=."'$date'.",Remarks=."'$remarks'.",Issuing date=."'$isdate'.",Issued to=."'$issuedto'.",Return Date=."'$returndate'." WHERE Report No.= ."'$id'."")
I have two pages. The first one I am sending data over to the second page. The second page I am using to edit the data sent over and other data within my database. I call for the data I sent over like this:
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
The issue is I have other data on the page that and whenever I edit any of this information, I want to be able to do an UPDATE query to save the new information. However, my query isn't working and I believe it is because my new input field's (data I didn't send over from the first page) data is not being recognized.
Whenever I var_dump the values, I get the data (and in the same format) as how I sent it over to this page.
Here is my code for the second page:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//print_r($stmt);
while($row = $stmt->fetch()) {
$productAmount = $row['amount'];
$productAvailable = $row['available'];
?>
<form name="update" method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit">Update Product Information</button>
</form>
<?php
}
var_dump($_POST);
if(isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
?>
When I do var_dump($_POST); I get the following values, clearly not including the amount and available data.
array(5) { ["id"]=> string(1) "4" ["first"]=> string(3) "Tom" ["last"]=> string(5) "Brady" ["product"]=> string(3) "Tea" ["edit"]=> string(4) "Edit" }
Why isn't all my data being recognized?
Nowhere in your script do you have:
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
Add those 2 lines just below: $product = $_POST['product'];
UPDATED
Is the form supposed to be populated by the database? Or the form itself? If by the database (initially), then you'll need to change all the $variables in the form to their corresponding field names from the table, ie. $row['id'], $row['first'], etc.
See below for update...
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$id = $_POST['id'];
$first = $_POST['first'];
$last = $_POST['last'];
$product = $_POST['product'];
$productAmount = $_POST['amount'];
$productAvailable = $_POST['available'];
$newId = filter_var($id, FILTER_SANITIZE_STRING);
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['update'])) {
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
$stmt->bindParam(6, $newId);
$stmt->execute();
}
if ( !empty($newId) ) {
$stmt = $dbc->query("SELECT * FROM users WHERE id='$newId' ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while( $row = $stmt->fetch() ) {
?>
<form action="" method="post">
<input type="text" name="id" value="<?php echo $row['id']; ?>">
<input type="text" name="first" value="<?php echo $row['first']; ?>">
<input type="text" name="last" value="<?php echo $row['last']; ?>">
<input type="text" name="product" value="<?php echo $row['product']; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<input type="submit" name="update" value="Update Product Information">
</form>
<?php
}
}
var_dump($_POST);
For the Undefined index just use a ternary in your form like so:
... value="<?php echo !empty($row['amount']) ? $row['amount'] : ''; ?>">
... value="<?php echo !empty($row['amount']) ? $row['available'] : ''; ?>">
Change these lines:
$stmt->bindParam(4, $productAmount);
$stmt->bindParam(5, $productAvailable);
to:
$stmt->bindParam(4, $_POST['amount']);
$stmt->bindParam(5, $_POST['available']);
So the result of cleaning up second part of your code would be this:
No need for a form name.
name="update" goes in the button's markup.
$_POST array now contains the new variables.
We check to make sure update is set before running the query.
<form method="POST">
<input type="text" name="id" value="<?php echo $newId; ?>">
<input type="text" name="first" value="<?php echo $first; ?>">
<input type="text" name="last" value="<?php echo $last; ?>">
<input type="text" name="product" value="<?php echo $product; ?>">
<input type="text" name="amount" value="<?php echo $row['amount']; ?>">
<input type="text" name="available" value="<?php echo $row['available']; ?>">
<button type="submit" name="update">Update Product Information</button>
</form>
<?php
}
if(isset($_POST['update'])) { // checking the button
$stmt = $dbc->prepare("UPDATE users SET first = ?, last = ?, product = ?, amount = ?, available = ? WHERE id = ?");
$stmt->bindParam(1, $_POST['first']);
$stmt->bindParam(2, $_POST['last']);
$stmt->bindParam(3, $_POST['product']);
$stmt->bindParam(4, $_POST['amount']); // now it is in the POST array
$stmt->bindParam(5, $_POST['available']); // same here
$stmt->bindParam(6, $newId);
$stmt->execute();
}
i want to show user specific data in html form(in text fields or in select list)
I have a function ShowUserInformation() in class MyClass:
function ShowUserInformation()
{
$query = "SELECT id, name, email FROM saloni WHERE id = '$_SESSION[ID_korisnika]'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)):
$id= $row['id'];
$name= $row['name'];
$email = $row['email'];
$address= $row['address'];
$address2= $row['address2'];
$address3= $row['address3'];
endwhile;
return $result;
}
My question is: How can i display value of $name, or $email, $id... on another page in text box or in select list?
If i do it in procedural way it works when i do this:
<input type="text" value="<?php echo $name ?>" name="name" class="" />
But, how can i display the $name,$email,$ID... in oop way? Is there a way to call it directly and not declare it as class variable and then call it.
i've included file, created object...
$my_class = new MyClass; //create an object of class
HTML - i've tried something like this...
<input type="text" value="<?php echo $my_class->ShowUserInformation($name)?>" name="name" class="" />
I'm new in PHP and oop so be easy with me :)
Thank you
If you only plan on one row being returned, then why not use mysql_fetch_assoc()
class MyClass{
public function GetUserInformation(){
$query = "SELECT id, name, email FROM saloni WHERE id = '$_SESSION[ID_korisnika]'";
$result = mysql_query($query);
$info = mysql_fetch_assoc($result);
return $info;
}
}
$class = new MyClass;
$info = $class->GetUserInformation();?>
<input type="text" value="<?php echo $info['id']?>" name="id" class="" />
<input type="text" value="<?php echo $info['name']?>" name="name" class="" />
Note: mysql_* functions are deprecated, and you should move to use MySQLi or PDO
First, change the function to get the data:
function ShowUserInformation()
{
// Assuming you need only one user, I have set "LIMIT" to "1"
$query = "SELECT id, name, email, address, address2, address3 FROM saloni WHERE id = '$_SESSION[ID_korisnika]' LIMIT 1";
$result = mysql_query($query);
return mysql_fetch_array($result);
}
Now, get the information:
$my_class = new MyClass;
$userData = $my_class->ShowUserInformation();
// HTML
<input type="text" value="<?php echo $userData['name']; ?>" name="name" class="" />
kindly try this:
<?php
$show_info=ShowUserInformation();
$data = $show_info->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){ ?>
<input type="text" value="<?php $row['name']; ?>" name="name" class="" />
<?php } ?>
OR
<?php $show_info=ShowUserInformation();
while ($row= mysql_fetch_assoc($show_info){ ?>
<input type="text" value="<?php $row['name']; ?>" name="name" class="" />
<?php } ?>