Fetching Multiple Rows, but Updating only One php - php

How do you update only one row when you fetch for multiple rows? I am lost on how to do this. I can fetch for one row, update and it works. However, I'm stuck for multiple rows.
Down below is my code
FETCH PHP:
//loop through for results
while($row = mysqli_fetch_array($data)){
echo "<tr><td>"
. $row['title']."<input type='hidden' value='".$row['title']."' name='title'>"
. "</td><td>"
. $row['author']
. "</td><td>"
. $row['summary']
. "</td><td>"
. $row['isbn']
. "</td><td>"
. "<img src='books/".$row['image']."' width='100%'/>"
. "</td><td>"
. "$<input type='text' value='".$row['price']."' size='8' class='pricetoright' name='price'>"
. "</td><td>"
. "<button type='submit' class='btn btn-default btngreen' name='update'>Update</button>"
. "</td><td>"
. "<button type='submit' class='btn btn-default btnred' name='delete'>Delete</button>"
. "</td></tr>";
}
UPDATE PHP:
// Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
die('SQL ERROR: Connection failed: '.mysqli_error($db));
}
$price = floatval($_POST["price"]);
$title = $_REQUEST["title"];
// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";
if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
mysqli_close($db);

Use form tag for each row. Also its better to use unique id to update row instead of title. So take hidden input of id.

You'd want to add a foreach() statement into your code. While it's a little unclear on your code here's a possible example:
foreach($_POST as $k=>$v){
if($k === "title"){
$title = $_POST["title"];
}
if($k === "price"){
$price = floatval($_POST["price"]);
}
// SQL to update a record
$query = "UPDATE books SET price = '$price' WHERE title = '$title'";
if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
}

Related

How to make the "delete button" not to delete the latest entry using PHP

My code delete the last row instead of deleting its own row, what to do?
i tried everything i can but it doesn't work please send help.
$sql = "SELECT id, name, ArticleTitle, Article FROM article";
if ($result = $conn->query($sql))
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .
$row["id"]. "</td><td>" ."<input type=hidden name=id value=".
$row["id"].">".
$row["name"] . "</td><td>" .
$row["ArticleTitle"]. "</td><td>" .
$row["Article"] ."</td><td>" .
"<button>View</button>". "</td><td>".
"<button type=submit name=login_user>Delete</button>" .
"</td></tr> " ;
// href="copytrade.php?id=$_GET['id']
}
echo "</form></table>";
and here is my connection.php script
if (isset($_POST['login_user'])) {
$id = mysqli_real_escape_string($conn, $_POST['id']);
if (empty($id)) {
array_push($errors, "ID is required");
}
// sql to delete a record
if (count($errors) == 0) {
$query = "DELETE FROM article WHERE id='$id'";
$results = mysqli_query($conn, $query);
}
if ($conn->query($query) === TRUE) {
echo "Record deleted successfully";
}
}
You're only going to want one ID hidden field (currently you have one for every row). You'll set its value to the id of the delete clicked before submitting the form. The way you're doing it right now sends every id as the same value to the page via $_POST and the last one overrides all of the others.

How to update a specific sql row from a html table

So I have a HTML table that grabs SQL data and shows the data in the HTML table. I have a button in the HTML table aswell witch reredicts to update.php. Here I want the row that the user pressed the button in updates the column "paid" to "Paid". Screenshot of the HTML table: https://emildeveloping.com/screenshots/outredden-pardonableness-amharic.png
The thing is that I can't get it working that it updates just that specific row, it updates all rows right now.
Ive tried searching around for same questions but haven't found any solutions.
This is the PHP code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "emildeveloping2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE purchases SET paid='Paid'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This is the PHP snippet of the HTML Table
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='purchases' class='purchases'><tr class='header'><th>Invoice ID</th><th>Customer ID</th><th>Product</th><th>Name</th><th>Email</th><th>Adress</th><th>Security Number</th><th>City</th><th>Zip Code</th><th>Country</th><th>Cost</th><th>Payment Plan</th><th>Status</th><th>Options</th></tr>";
// Visa datan
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["customerid"]. "</td><td>" . $row["product"]. "</td><td>" . $row["name"]. "</td><td>" . $row["email"]. "</td><td>" . $row["adress"]. "</td><td>" . $row["securitynumber"]. "</td><td>" . $row["city"]. "</td><td>" . $row["zipcode"]. "</td><td>" . $row["country"]. "</td><td>" . $row["cost"]. "</td><td>" . $row["paymentplan"]. "</td><td>" . $row["paid"]. "</td><td><a class='fas fa-check-square' href='update.php'></a></td></tr>";
}
echo "</table>";
} else {
echo "There is no active calls.";
}
I want just a specific row to update where id = id.
You need to update two things:
Add the id of the row you want to update as a GET argument in the link so it is passed to PHP script:
<a class='fas fa-check-square' href='update.php?row_id='.$row["id"].'>
Now if you check the links, each of them should be unique: update.php?row_id=1, update.php?row_id=2, etc.
Handle this added url parameter in the PHP script so it is used to select desired
row in database table:
$sql = "UPDATE purchases SET paid='Paid' WHERE id=".$_GET['row_id'];
If you get it working use http://php.net/manual/en/mysqli.prepare.php prepare method instead of query, so your code is not prone to sql injecton.
Something like this:
$mysqli->prepare("UPDATE purchases SET paid='Paid' WHERE id=?")) {
$stmt->bind_param("i", $_GET['row_id']);
$stmt->execute();
Another thing would be using POST requests instead of GET links to prevent CSRF vulnerability.

Deleting a row with Php & MySQL

I am new to php and SQL and just toying around with a project for my own understanding of accessing, updating and deleting data from my Database.
I have managed to show the selected data, create a button to delete a specific Id but really needing some assistance with deleting the selected row or record instead of hard coding in the ID in my delete php script.
Here is an example of my script:
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is the delete.php
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='6' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
what I would like it to do is, delete the row from which you hit the delete button from and not just delete the row I have specified in the delete.php script. I understand HOW it should work by posting the id but not sure how to do it.
Do like this
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span><a href='deleteMember.php?id=".$row['id']."'>Delete</a></span>" .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
in place of your form use this
DELETE
and in your delete query must be like below
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
or stay in your post form with:
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<input type='hidden' name='myid' value='".$row['id']."' />
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
And in your delete.php :
<?php
$id=(int) $_POST['myid'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id=".$id;
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
No need to add extra form element for Delete or Edit purpose. Try this way to pass the id of row for Eelete or Edit operation
while($row = $result->fetch_assoc())
{
$id=$row['id'];// capture your row id & pass to your delete & edit
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<a href='deleteMember.php?id=<?=$id;?>'>Delete</a>
</span>" . " " .
"<span class='editMember'>
<a href='editMember.php?id=<?=$id;?>'>Edit</a>
</span>" .
"<br>
</div>";
}
EDIT:
Then catch the id on your relevant page for your operation.
//deleteMember.php
<?php
$id=$_GET['id'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$id."'";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Note: Please Use Prepared Statements of PDO or MYSQLi instead to avoid SQL Injection and manual escaping.

How to make a link this is connected to database in php

I am trying to make a php script which will get clients data from database in a table. the script works fine and is getting database fields correctly. Now i want to add a link beside every client info. The link should be like www.domain.com/check?clientid=$id&number=$phonenumber
How should i do this?
its a table and clients details are arranged in order. Please help me?
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname, phonenumber, city, country, email FROM clients ORDER BY ID ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>Phone Number</th><th>Country</th><th>Email</th><th>Send SMS</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"]. "</td><td>" . $row["phonenumber"]. "</td><td>" . $row["city"]. " "
. $row["country"]. "</td><td>" . $row["email"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I agree with Marcosh (in the comments), so that would give you this code (between the if(...) { and } else):
echo "<table><tr><th>ID</th><th>Name</th><th>Phone Number</th><th>Country</th><th>Email</th><th>Send SMS</th><th>Link to page</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"]."</td><td>" . $row["phonenumber"]. "</td><td>" . $row["city"]. " ". $row["country"]. "</td><td>" . $row["email"]. "</td><td>Click me!</td></tr>";
}
echo "</table>";
Note 1: This will add a link with the text "Click me!". I think you may want to change that. You may also want to change the header (currently "Link to page")
Note 2: If you use php 5.5 or later, you can also use
echo "blablabla<td>{$row['id']}</td>etc..."
instead of
echo "blablabla<td>" . $row['id'] . "</td>etc..."
Thanks for help #ivo and i have learned how to get this thing done:
<td><form action='https://control.domain.com/api/sendhttp.php' method='GET'><input type='hidden' name='authkey' value='74685AiSz3dkBX5467773f'><input type='hidden' name='mobiles' value='" . $row['phonenumber'] . "'><input type='hidden' name='sender' value='hostbi'><input type='hidden' name='route' value='4'><textarea name='message' cols='55'>Leave a message</textarea><input type='submit' value='Click me!'></form></td>

Increase in Value button "mrk2"

Update post for: Increase in Value button
I made a post asking about how make an increase value button. I got one decent answer, I tried it and it didn't work.
Original:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td>" . $row['downvotes'] . "</td>";
}
echo "</table>";
Current:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['upvotes'] . "'>Upvote [" . $row['upvotes'] . "]</a></td>";
echo "<td><a href='action.php?do=down&id=" . $row['downvotes'] . "'>Downvote [" . $row['downvotes'] . "]</a></td>";
}
echo "</table>";
mysqli_close($con);
?>
action.php:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id+1 . "'");
}
elseif ($action=="down") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id-1 . "'");
}
else {echo "error: 002 / voting error";}
mysqli_close($con);
?>
As you can see I implemented the changes that were recommended and that could of worked, but they didn't rather than updating the data it did nothing. As when pressing "upvote"/"downvote" it grabbed the current value as $id rather than the position of the data to update it.
tl;dr: I tried a fix from the previous thread, it didn't do anything. Help please?
sorry if I have been unclear, let me give it another try:
You insert a link into your table, which calls an action.php. The action.php updates the database. The information needed for updating are passed as GET-parameters.
For updating the database, you will need to know WHAT to do, and secondly, WHICH database entry is actually affected.
Step by step:
First, you have to insert the links into your table:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th></th><th>Down Votes</th><th></th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['key'] . "'>Upvote</a></td>";
echo "<td>" . $row['downvotes'] . "</td>";
echo "<td><a href='action.php?do=down&id=" . $row['key'] . "'>Downvote</a></td>";
echo "</tr>";
}
echo "</table>";
On clicking the link, we are sending two pieces of information to the action.php.
The action we have to perform, either up- or downvoting. It tells us WHAT to do.
The id of the element we have to up- or downvote. The id tells us WHICH element is affected, and not the number of votes an element has.
As mentioned in my answer to your previous post, $row['key'] should contain the primary key of your database, e.g. an unique identifier. You should have such an identifier in your database, otherwise you cannot make a reference to a specific database entry. However, as we want to update the vote count for a very specific database entry, we need a possibility to uniquely identify this database entry.
In your action.php, you have to do the following:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
mysqli_query($con, "UPDATE champion_counters_b SET upvotes = upvotes + 1 WHERE key = " . $id . "'");
}
elseif ($action=="down") {
mysqli_query($con, "UPDATE champion_counters_b SET downvotes = downvotes - 1 WHERE key = " . $id . "'"); }
else {echo "error: 002 / voting error";}
mysqli_close($con);
We use the id value to select the database entry we have to update. This is done by WHERE key = $id in the UPDATE-statement. The current vote count is taken from the database itself - there is no need to pass the current vote count in the GET-parameters.
After you have updated your database, you can redirect to the original page and reload your table. Then, the updated vote count should show up.

Categories