Printing text to textbox and input from sql database in php - php

I would like to ask if someone could help me with this problem.
I want to prefill the input and textbox from the SQL database. I have tried it many times and I didn't succeded.
This is the code:
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['id'].">".$row['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
?>
Thank you in advance.

Ahhh! You have a While Loop INSIDE a While Loop!!
And both are processing mysqli_fetch_array($result) and therefore the inner loop destroys the $result used in the outer loop.
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
// changed code here
// 1 you dont need to connect twice
//$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
// use different var here
// and then use it in the related function calls
$result1 = mysqli_query($conn, $query);
if ($result1) {
// and of course use a different var to hold the row data
// so you dont overwrite that also
while ($row1 = mysqli_fetch_array($result1)) {
echo "<option value=".$row1['id'].">".$row1['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
Seperate issue, you dont appear to have a <form> and </form> tag in this code. Without that the data placed in input fields will never be transmitted as a form to the PHP script for processing
BIG NOTE
Your script is open to SQL Injection Attack.
Even if you are escaping inputs, its not safe!
You should consider using prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenated values
So to prepare the relevant dangerous query
$query = 'SELECT nazev, popis FROM recepty WHERE id = ?';
$stmt = $conn->prepare($conn, $query);
$stmt->bind_param('i', $_POST['id_recept']);
$stmt->execute();
$result = $stmt->get_result();
. . .

Related

Table row delete button

When I try the delete button I get no errors and the page refreshes but the data won't be deleted, so I think the problem is in passing along the id from a row.
None of the other solutions have worked for me so far. This is the table body.
<tbody>
<?php
$server = "localhost";
$user = "Website";
$pass = "pass";
$db = "db";
$conn = new mysqli($server, $user, $pass, $db);
if ($conn->connect_error)
{
die("connection to database failed");
}
$query = "SELECT * FROM koppeling";
$result = mysqli_query($conn, $query);
while($row = $result-> fetch_assoc())
{
echo "<tr>";
echo "<td>".$row['Wagon_ID']."</td>";
echo "<td name='wagon'>".$row['EPC']."
<a href='delete.php' class='table-button'
id='".$row['id']."'>Delete</a>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
delete.php file:
<?php
$id = $_GET['id'];
$server = "localhost";
$user = "Website";
$pass = "pass";
$db = "db";
$conn = new mysqli($server, $user, $pass, $db);
if ($conn->connect_error)
{
echo "Conn db failed";``
}
$query = "DELETE FROM koppeling WHERE id='$id';";
try
{
mysqli_query($conn, $query);
mysqli_close($conn);
header('Location: koppelen.php');
}
catch (Exception $e)
{
echo "$e";
}
?>
Can anyone help me figure out what is wrong, I've been stuck on this quite a while now.
Instead if this
while($row = $result-> fetch_assoc())
{
echo "<tr>";
echo "<td>".$row['Wagon_ID']."</td>";
echo "<td name='wagon'>".$row['EPC']."
<a href='delete.php' class='table-button'
id='".$row['id']."'>Delete</a>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
Write this
while($row = $result-> fetch_assoc())
{
echo "<tr>";
echo "<td>".$row['Wagon_ID']."</td>";
echo "<td name='wagon'>".$row['EPC']."
<a href='delete.php?id=".$row['id']."' class='table-button'
id='".$row['id']."'>Delete</a>";
echo "<td>";
echo "</td>";
echo "</tr>";
}
It would be better if you used form with POST request or ajax instead of links.
If you really want to do it this way you can add query string to your href attribute.
$url = "delete.php?id=" . $row['id'];
<a href="<?php echo $url ?>" class='table-button'
id='".."'>Delete</a>";
You have to change the below line
$query = "DELETE FROM koppeling WHERE id='$id';";
to
$query = "DELETE FROM koppeling WHERE id='".$id."';";
so that id value will be properly populated in the query

Form submission in while loop result is coming only in the last row?

<?php
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";
$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);
if ($Connection === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlusers = "select * from user";
$result = mysqli_query($Connection, $sqlusers);
echo "<form method='POST'>";
while($rowuser = mysqli_fetch_array($result)){
$user = $rowuser['FirstName'];
echo "<input type='text' name='firstName' value='$user' readonly>";
echo "<select name='attendanceType'>";
$sqltype = "select * from attendancetype";
$resultaType = mysqli_query($Connection, $sqltype);
while($rowtype = mysqli_fetch_array($resultaType)){
echo "<option>";
echo $rowtype['name'];
echo "</option>";
}
echo "</select>";
echo "<br>";
}
echo "<input type='submit' name='submit' value='submit'>";
echo "</form>";
?>
Users table.
INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul#zzz.xxx', 'Rahul#123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh#xxx.xxx', 'Mahesh#123', 'Delhi');
attendancetype table:
INSERT INTO `attendancetype` (`attendanceTypeID`, `name`) VALUES
(0001, 'Present'),
(0002, 'Absent');
How can I inserting data into table on a single submission of form?
your code has one mistake. If you are looping form elements, you must achieve, that every input has the unique name.
$i = 0;
while($rowuser = mysqli_fetch_array($result)){
$user = $rowuser['FirstName'];
echo "<input type='text' name='firstName[".$i."]' value='$user' readonly>";
echo "<select name='attendanceType[".$i."]'>";
$sqltype = "select * from attendancetype";
$resultaType = mysqli_query($Connection, $sqltype);
while($rowtype = mysqli_fetch_array($resultaType)){
echo "<option>";
echo $rowtype['name'];
echo "</option>";
}
echo "</select>";
echo "<br>";
$i++;
}
process form with:
<?php
mysqli_set_charset($Connection, "utf8");
foreach($_POST['firstName'] as $i => $user) {
$sql = "insert into table set attendance_type = '".mysqli_real_escape_string($Connection, $_POST['attendanceType'][$i])."' where user='".mysqli_real_escape_string($Connection, $user)."'";
mysqli_query($Connection, $sql);
}
?>
escapeFunction is used as a refferer to the fact, that you should escape somehow (there are more ways) every input and it needs to be replaced or defined

Update whole table in one query

If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:
<form action='update.php' method='post'>
<table border='1'>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exchange";
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($conn,"utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
echo "</tr>";
}
}
$conn->close();
?>
<table>
There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...
I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:
if ($result->num_rows > 0) {
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "</tr>";
}
}
On the php side to process the input, you can do something like this:
$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
//do insert with $id
}

PHP Issue Updating Database On Button Click

Hello I'm making a shop in php where I populate the shop with a while loop so all the shop items from my database are displayed. This works fine but I have an issue when I try to update the stock count and money left on the account when I press the buy button.
The $ItemCost variable only saves the last populated item cost and I'm not sure how to save the cost of each item to insert it into the database.
Also the $StockCount variable sets the stockcount to 1.
How can I fix this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
}
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money = $NewTotal WHERE ID = $ID";
if(isset($_POST['Buy'])){
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
As #Sean said, you can do this like :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['Buy'])){
// update stock and money
$ID = $_POST['ID'];
$Money = $_POST['Money'];
$ItemCost = $_POST['ItemCost'];
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money =
$NewTotal WHERE ID = $ID";
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
// display items
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER
BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<form method='post' action=''>";
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='hidden' name='Id' value='".$ID."'/>";
echo "<input type='hidden' name='Money' value='".$Money."'/>";
echo "<input type='hidden' name='ItemCost' value='".$ItemCost."'/>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
echo "</form>";
}
}
$conn->close();
Assuming you don't want ajax, and you don't want js, but only a 'buy' button under each item which will reopen the entire page, then you want something like this. This is pseudo code:
//FIRST we need to process the form:
<?php
if(isset($_POST['submit'])){
$itemId = $_POST['id'];
//do the stuff. Remember about escaping $itemId, or using prepared statements
//select... from where id = $itemId
}
?>
//now get the items:
<?php
$GatherItems = ...
?>
//now the html:
<?php
while($row = $result->fetch_assoc()) {
?>
<form method = 'post'>
<div class='test'><?=$ItemName?></div>
...
<input type = 'hidden' name = 'itemId' value = '<?=$ID?>'>
<input type = 'submit' name = 'submit' value = 'Buy'>
</form>
}
?>

Why do I get an undefined variable error when trying to use PHP in two sections of a page?

I am trying to use PHP in two different parts of a page. But when I try to load the page I receive the error: undefined variable $conn. Why am I getting this error?
<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\"
class=\"amount-type\"
placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
You use $conn at the top of your script
$result = mysqli_query($conn, $sql);
Yet you define it further down
$conn = mysqli_connect($servername, $username, $password, $dbname);
You'll need to move that section up to the first before you can run any queries.
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\" class=\"amount-type\" placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
You're defining and connecting to the database after you try to use it. Move the connection part above the query. If this is the only place that you will be using the connection the page then this is fine. But if other pages or sections of the page will use the connection you should look at placing this in a common file that is included at the top of every page that uses it.
<tbody>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\" class=\"amount-type\" placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
I'd be pretty sure that you need to define $conn before you call it in the top part of the php code.
PHP is loaded and executed sequentially... You are defining $conn after using it. Try doing it before. I.e.: Move the second blob of PHP above the first one.
For more on PHP execution order, check out this question.

Categories