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.
Related
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.
I'm learning PHP right now and connecting to MySQL. I'm able to connect to a table called "info" and display the "date", "time", and "data" of each row, along with 2 extra columns that will allow the user to download the respective "data" into a txt and csv. This is where I'm completely lost on how to achieve that.
My understanding is that since it'll be a clickable link, I will have to use "href=" and will link that to a separate php that I create that will download that row's data, right? But then how does that new php file know which row to download from? I'm guessing I need to pass the row number it is to the other file?
Greatly appreciate it if anyone can lead me in the right direction or have examples. Thanks!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date, time, data FROM info";
$result = $conn->query($sql);
echo "<table border='1'>";
echo "<tr><td> Date </td><td>Time</td><td>Data</td><td> Download text </td><td> Download csv</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" . $row["time"]. "</td><td>" .$row["data"] ."</td><td><a href='NEEDTXTFILE.php'>".$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
} else {
echo "0 results";
}
Assuming you select also the id value
$sql = "SELECT id, date, time, data FROM info";
....
you could add the id to your href eg:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" .
$row["time"]. "</td><td>" .
$row["data"] .
"</td><td><a href='NEEDTXTFILE.php?id=" . $row["id"] . "'>".
$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".
$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
then in your NEEDTXTFILE.php you can obtain the id in $_GET['id']
I am new to PHP and MySQL and hope someone can help me with this.
I have a MySql db with a table "TranslationsMain" and the following PHP query.
This returns all the items from column "German" (incl. the corresponding ID) from the db table and works correctly so far.
Instead of echoing the whole list (I just did this here for testing), **how can I store the results in an array in a way that each item within the array is stored with its value and a unique ID + how I can I echo specific items from this array by referring to their ID ?
Example:
I would like to echo the item value for ID "xyz" from this array (without calling the db again since this will be needed for multiple items on the page).
My PHP:
<?php
require_once("includes/header.php");
$tblTranslations = "TranslationsMain";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM " . $tblTranslations;
$translations = $conn->query($sql);
// for testing only
if($translations->num_rows > 0){
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
}
echo "</table>";
}else{
echo "0 results";
}
$conn->close();
?>
Update:
What I am looking for here is how to create a two dimensional array and how to fetch from it.
Many thanks in advance,
Mike
if($translations->num_rows > 0){
$result_arr = array();
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
$result_arr[] = $translation;
}
echo "</table>";
}else{
echo "0 results";
}
// now you can iterate $result_arr
foreach($result_arr as $row){
echo "<tr><td>" . $row["ID"] . "</td><td>" . $row["German"] . "</td></tr>";
}
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);
}
}
I tailored this page mysql.php but for the time being it appears blank-white on the browser.
<html>
<head>
<title> MySQL Test </title>
</head>
<body>
<?php
$username = "username";
$password = "pass";
$hostname = "localhost";
$dbname = "StudentLessons";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL <br>";
$query = "SELECT * FROM Teacher GROUP BY bathmida";
$result = mysql_query($query);
echo "<table>"; // start table in html
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . row['onoma'] . "</td><td>" . row['epitheto'] "</td><td>" . row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
echo "</table>"; //close table
mysql_close(); //close the db connection
?>
</body>
</html>
Now I know for a fact that
The connection is legit.
The query is working because I tested them both.
I also advised another question here on [so] and it seems I am missing something important. The <tr><td> tags in HTML are set as they should be, so what might be the problem?
By the way, isn't there any other way to automate the process a bit? i.e. to develop a form that can support more queries etc.?
You forgot to add $ in below code
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . row['onoma'] . "</td><td>" . row['epitheto'] "</td><td>" . row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
correct code is:
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . $row['onoma'] . "</td><td>" . $row['epitheto'] "</td><td>" . $row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
You miss $, and you must use like this : $row->onoma
echo "<tr><td>" . $row->onoma . "</td><td>" . $row->epitheto"</td></tr>