Form values not posting - php

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();
}

Related

PHP CRUD - Update function

I am creating the BindableCollection class which implements IBindableCollection.
What I want to do is CRUD operations above the collection (array of associative arrays). I have all of the CRUD functionallity, but I lack update function which doesn't work.
Code
public function updateFirstWhere($attr, $value, $updateCallback) {
$i = 0;
foreach($this->value as $data) {
if($data[$attr] == $value) {
call_user_func_array($updateCallback, $this->value[$i]);
return;
}
$i++;
}
}
When I pass the $this->value[$i] (which is all of the data inside collection) to the callback function and I do something like that:
public function deleteThePerson($sender) {
$this->collection->updateFirstWhere("id", $sender->data_id, function(&$data) {
$data["name"] = "durisvk";
});
}
I don't see the change in the data.
I want to set the name to durisvk but I can't.
Any Ideas Please?
</head>
<body>
<?php
// UPDATE CRUD element.
$idc = -1;
$naam = "";
$merk = "";
$typ = "";
$kl = "";
$con = new PDO ("mysql:host=localhost;dbname=cars_database", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_GET["action"])) {
if($_GET["action"] == "edit") {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$statement = $con->prepare("UPDATE cars_assigment SET Name=?, Brand=?, Type=?, Color=? WHERE Id = ?");
$statement->bindValue(1, $_POST["Name"]);
$statement->bindValue(2, $_POST["Brand"]);
$statement->bindValue(3, $_POST["Type"]);
$statement->bindValue(4, $_POST["Color"]);
$statement->bindValue(5, $_POST["Id"]);
$statement->execute();
}
$statement = $con->prepare("SELECT * FROM cars_assigment WHERE Id = ?");
$statement->bindValue(1, $_GET["Id"]);
$statement->execute();
$record = $statement->fetchObject();
if($record != false) {
$idc = $record-> Id;
$naam = $record-> Name;
$merk = $record-> Brand;
$typ = $record-> Type;
$kl =$record-> Color;
}
}
}
?>
<h1> Update </h1>
<form method="POST">
ID: <input type="text" name="Id" value="<?php echo $idc ?>">
Naam: <input type="text" name="Name" value="<?php echo $naam ?>">
Brand: <input type="text" name="Brand" value="<?php echo $merk ?>">
Type: <input type="text" name="Type" value="<?php echo $typ ?>">
Color: <input type="text" name="Color" value="<?php echo $kl ?>">
<input name="Id" type="hidden" value="<?php echo $idc; ?>"> </input>
<input type="submit" value="Save"> </input>
</form>
</body>

PHP cannot insert variable into database

Problem is in the INSERT INTO statement. I'm trying to insert $today, $id, $stat_sum, $klientas. Everything is inserting except the $id. After I press the submit button, everything is inserting, but where there should be the $id, it shows NULL. I tried to echo $id , it showing normally as it should be.
$today = date('Y-m-d G:i:s');
if( isset($_GET['pas']) )
{
$id = $_GET['pas'];
$res= mysql_query("SELECT MAX(statymo_suma) FROM statymai WHERE aukciono_id = '$id'");
$row= mysql_fetch_array($res);
echo $id;
}
if( isset($_POST['stat_sum']) )
{
echo '<input type="hidden" name="id" value="<?php echo $row[2]; ?>">';
$stat_sum = $_POST['stat_sum'];
$id = $_POST['id'];
$res1= mysql_query("SELECT kliento_id FROM klientai WHERE vartotojo_vardas = '$user_check'");
$row1 = mysql_fetch_assoc($res1);
$klientas = $row1['kliento_id'];
$sql = "INSERT INTO statymai (statymo_laikas,aukciono_id,statymo_suma,kliento_id) VALUES ('$today','$id','$stat_sum','$klientas')";
$res =mysql_query($sql)
or die("Negaliu redaguoti".mysql_error());
//echo "<meta http-equiv='refresh' content='0;url=redaguoti.php'>";
}
?>
<form action="pasiulymas.php" method="POST">
Statymo suma: <input type="text" name="stat_sum" value="<?php echo $row[0]; ?>"><br />
<input type="hidden" name="id" value="<?php echo $row[2]; ?>">
<input type="submit" value=" =Redaguoti "/>
</form>
var_dump($sql) result:
string(123) "INSERT INTO statymai (statymo_laikas,aukciono_id,statymo_suma,kliento_id) VALUES ('2015-12-20 15:04:50','','123456','KL01')"

How to Edit a MySQL Data base from a PHP Site

I have built a database named "artStore" and a table within that database named "inventory". I've been able to figure out how to create a new entry to the database, but I'm trying to create a page that can edit those entries.
Here is "inventory" the table I created:
$sql = "CREATE TABLE inventory (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(30),
category VARCHAR(30),
seller VARCHAR(30)
)";
Here is what I'm currently trying:
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
What I'm trying in update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
$connection->close();
Try the below code I added hidden field on form and changes on your sql query
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultId = $row["id"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<input type="text" name="update_id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
In update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$updateId = $_POST['update_id'];
$sql = "UPDATE inventory set product = '$product',category='$category',seller='$seller' WHERE id = '$updateId'";
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
$resultId = "product_id";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultid = $row["id"];
}
} else {
echo "No Results";
}
?>
You were using $resultId in the form but you have not declared and assigned a value to it in the loop.
<form action="update.php" method="POST">
<input id="id" type="hidden" name="id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input type="submit" value="Update My Record">
</form>
<!-- Instead of passing the ID in textbox with display: none you can pass it directly in hidden -->
<?php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$product_id = $_POST['id'];
if($product_id!='')//MEANS WE HAVE TO UPDATE THE RECORD
{
// UPDATE QUERY WILL UPDATE THE SAME RECORD ONLY MATCHING THE UNIQUE PRODUCT ID
$sql = "UPDATE inventory SET product = '$product', category = '$category', seller = '$seller' WHERE id = '$product_id' LIMIT 1";
if ($connection->query($sql) === true) {
echo "Updated Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
else// If id is blank it means you have a new record
{
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
$connection->close();
?>

Retrieve data from database using mysqli

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 ...

PDO UPDATE creates a new record instead of updating one

I'm using the following code to update a record. Bad thing is that it's not updating a record but it's adding a new record.
What am I doing wrong? I want it to update the record and not create a now one.
My modify url looks like this: http://randomsite.com/modify.php?id=1
Modify.php code:
<?php
require_once("connect.php");
$query = "SELECT * FROM cars WHERE id = :id";
$result = $odb->prepare($query);
$result->execute(array(':id' => $_REQUEST['id']) );
while ($row = $result->fetch(PDO::FETCH_ASSOC)) { ?>
<h1>Modify a car</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Brand: <input type="text" name="brand" value="<?php echo $row['brand']; ?>" /><br />
Model: <input type="text" name="model" value="<?php echo $row['model']; ?>" /><br />
Year: <input type="text" name="year" value="<?php echo $row['year']; ?>" /><br />
ID: <input type="text" name="id" value="<?php echo $row['id']; }?>" /><br />
<input type="submit" value="Modify" />
</form>
<?php
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$q = "UPDATE cars WHERE id = $_GET[id] (id, brand, model, year) VALUES(:id, :brand, :model, :year)";
$query = $odb->prepare($q);
$results = $query->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year,
));
}
?>
Your SQL should look something more like this:
$q = "UPDATE cars SET
id = :id,
brand = :brand,
model = :model,
year = :year
WHERE id = :oldid";
$query = $odb->prepare($q);
$results = $query->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year,
":oldid" => $_GET['id'],
));
As a side note, try not to put variables in your SQL (like your $_GET['id']), part of the idea of using PDO is to avoid doing that.
Got it to work!
Working code:
<?php
require_once("connect.php");
$query = "SELECT * FROM cars WHERE id = :id";
$result = $dbh->prepare($query);
$result->execute(array(':id' => $_REQUEST['id']) );
while ($row = $result->fetch(PDO::FETCH_ASSOC)) { ?>
<h1>Modify a car</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Brand: <input type="text" name="brand" value="<?php echo $row['brand']; ?>" /><br />
Model: <input type="text" name="model" value="<?php echo $row['model']; ?>" /><br />
Year: <input type="text" name="year" value="<?php echo $row['year']; ?>" /><br />
ID: <input type="text" name="id" value="<?php echo $row['id']; }?>" /><br />
<input type="submit" value="Modify" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])) {
$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$id = $_POST['id'];
$queryupdate = "UPDATE cars SET
brand= :brand, model= :model, year= :year WHERE id= :id";
$q = $dbh->prepare($queryupdate);
$q->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year));
//Send them back to the page they were at/
header("location:admin.php");
}
?>

Categories