How to update database with entire html table (PHP, MySQL) - php

I have been struggling with this for several days now. I have searched on how to update tables and have managed to get as far as to update rows, but only the last one in the table. So now i am trying to get a loop that loops through all the inputs and updates the database with the inputted values. I think the code that needs to be corrected is located near the end of the code
What i want to do:
Get/display database in html table
Change values of certain columns
Update the database table using a submit button which updates every row in database
Here is a picture of what the table looks like in web view:
<?php
//Connect to database
include '../db/connect.php';
?>
<form action='test7.php' method="post">
<table border='1'>
<?php
$result = $MySQLi_CON->query("SELECT * FROM users");
echo "<tr>";
echo "<td colspan='3'>CLASS 1</td>";
echo "</tr>";
//All table rows in database presented in html table
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td><input type='hidden' name='user_id[]' value='".$row['user_id']."' /></td>";
echo "<td>username :<input type='text' name='username[]' value='".$row['username']."' /></td>";
echo "<td>email :<input type='text' name='email[]' value='".$row['email']."' /></td>";
echo "<td>rank :<input type='number' name='rank[]' value='".$row['rank']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
<table>
</form>
<?php
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
header('Location: test7.php');
}
}
?>
When I press the UPDATE button, i get PHP Notice: Array to string conversion in....
It refers to line 30 which is this line:
$query = "UPDATE user SET rank=$_POST[rank][$row] WHERE user_id=$value ";
EDIT: Edited the code above to the working code. Thank you #Frayne Konok for your help.

You are very close.
The issue is that in this code $_POST[rank][$row] - rank is an undefined constant. You need it to be a string, like so $_POST['rank'][$row]. Also, pull the $POST variable out of the query directly to allow typecasting - you should always be very uncomfortable when you see a query that has $_POST data directly:
if(isset($_POST['update'])){
foreach ($result as $row => $value) {
// typecast to a number with decimals below. If you only need integers, than use (int)
$rank = (float)$_POST['rank'][$row];
$query = "UPDATE user SET rank={$rank} WHERE user_id={$value}";
$MySQLi_CON->query($query);
}
}
However, it would be better to use mysqli prepared statements rather than insert the variables directly - as it stand, the above code is vulnerable to SQL Injection attacks.
Your code should be modified to look something like so to prevent sql injection attacks:
if(isset($_POST['update'])) {
$stmt = $MySQLi_CON->prepare("UPDATE user SET rank= ? WHERE user_id= ?");
foreach ($result as $row => $value){
$stmt->bind_param('di', $_POST['rank'][$row], $value);
$stmt->execute();
}
$stmt->close();
}

You did a great mistake here, Why you use the $result in foreach
loop?? FRom where the $result comes?? The $result is the resource
of the sql query.
Try this:
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
}
}
Try with this and let me know if there is any problem.

Related

PHP MySQL save a row id to a database based on user checkbox

I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>

Foreach is taking last item of input text field

Good afternoon StackOverflowers,
I've got a pretty simple question. (I guess:))
Everytime I submit a form with many other input fields it takes the last value of a input field.
I had a similar problem a month ago, but I fixed it somehow.. I just can't fix this problem..
Below you can see my HTML form. (No markup, I know)
<?php
include_once("database.php");
$sql = "SELECT * FROM statements";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
echo "<b>";
echo $row['question'];
echo "<br/></b>";
$sqlA = "SELECT * FROM question_answer WHERE question_id =" . $row['id'];
$stmtA = $db->prepare($sqlA);
$stmtA->execute();
$rowsA = $stmtA->fetchAll(PDO::FETCH_ASSOC);
echo "<form id='modify' name='modify' action='modify.php' method='POST'>
<div id='answers'>";
foreach($rowsA as $rowa){
if($rowa['correct_answer'] == 1){
$rowAnswer = $rowa['answer'];
$rowId = $rowa['question_id'];
echo "<input type='text' checked value='" . $rowAnswer . "' name='" . $rowId."' style='background:lightgreen;'><br/>";
echo "</div>";
}
else{
$rowFalseId = $rowa['question_id'];
echo "<input type='text' value='" . $rowAnswer . "' name='" . $rowFalseId."'><br/>";
}
}
}
?>
<input type='submit' name='modify_answers' value="Modify Answers">
</form>
Below you can see my Update Query;
<?php
include_once("database.php");
// foreach($_POST as $val){
// print_r($val);
// }
$sql = "SELECT * FROM statements";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$sqlA = "SELECT * FROM question_answer where question_id =" . $row['id'];
$stmtA = $db->prepare($sqlA);
$stmtA->execute();
$rowsA = $stmtA->fetchAll(PDO::FETCH_ASSOC);
foreach($rowsA as $rowa){
foreach($_POST as $id => $value){
$update = "UPDATE question_answer SET answer = '".$value."' WHERE question_id ='". $id."'";
$stmt = $db->prepare($update);
$stmt->execute();
}
}
}
?>
Everytime It submits to the modify.php file it updates the last value of a input field.
In example if I have 16 input fields, it takes the 4th, 8th, 12th and 16th value of the input field.
So the problem is probaly with the name of the input field, but it could be also the modify.php..
Any help is appericiated! I'm struggling days with this easy problem:(
Thanks in Advance Guys!!
I think I can see what's happening here. You need to move this line...
$rowAnswer = $rowa['answer'];
... so it doesn't fall within your if statement (move them up above it). It's only been assigned, currently, if $rowa['correct_answer'] == 1 evaluates to true.
It is fixed guys! Thanks for your help.. #d0ug7a5 thanks for the answer, that helped me. But my main problem was that I was getting the Question_id instead of the id. Thanks!!

Deleting database values Using PHP, not working

I am trying to delete multiple values from my form (its a car rental system, where I want to give the staff the ability to delete a car from the record). I am new to PHP but this is what I have right now.
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$query = "SELECT * from car";
$result = mysql_query ($query);
echo ("<form action=\"deleting2.php\" method=\"GET\">");
echo "<table id = 'table-3'>";
echo "<thead>";
echo "<th>Car ID</th>
<th>Car Name</th>
<th>Fuel Type</th>
<th>Transmission</th>
<th>Engine Size</th>
<th>Doors</th>
<th>Total</th>
<th>Available</th>
<th>Date Added</th>
<th>Delete</th> ";
echo "</thead>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
echo "<tbody>";
echo "<tr>";
echo "<td>$row->ID</td>";
echo "<td>$row->CARNAME</td>";
echo "<td>$row->FUELTYPE</td>";
echo "<td>$row->TRANSMISSION</td>";
echo "<td>$row->ENGINE_SIZE</td>";
echo "<td>$row->DOORS</td>";
echo "<td>$row->TOTAL</td>";
echo "<td>$row->AVAILABLE</td>";
echo "<td>$row->DATEADDED</td>";
echo "<td><input type='checkbox' name='delete[]' value='$row->ID' /></td>";
echo "</tr>";
echo "</tbody>";
}
echo ("<tr><td colspan='6' align='center'><input type=\"submit\" value=\"Delete \"></td> </tr></table></form>");
echo "</table>";
mysql_close ($link);
?>
Now,when I do press the delete button, it goes to my php page called 'deleting2.php' as mentioned in the form action, which has the following code:
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$ID='$_GET[ID]';
// DELETE ANY RECORDS IN DATABASE
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
?>
The problem is, it is NOT deleting anything from the my database. The URL in the address bar when the deleting2.php is being processed, is:
http://www.computing.northampton.ac.uk/~11430900/a1/webpages/deleting2.php?delete[]=6
Which according to my knowledge, selects the values that were ticket. Here, I had checked the box, which had a corresponding ID value of 6. So, check-box DOES work, it just does not do anything to the database, does not delete the value. I have tried many tutorials but I can't delete it using check-boxes. Any help would be much appreciated.
You don't need to itrate through following loop as mentioned in your question
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
just to the following.
change your form method to POST.
use the following code. implode is necessary as $_POST['delete'] will be an array
if(isset($_POST['delete']) && count($_POST['delete']) > 0) {
$query=("DELETE FROM car WHERE ID in ('".implode(',',$_POST['delete'])."')");
$result1 = mysql_query($query);
}
Your data needs sanitizing but this should be Ok if you expect the ID to be a number:
$id = (int)$_GET['ID'];
$query=("DELETE FROM car WHERE ID=$id");
You really need to look at the rest of your code for SQL injection attacks.
First of all, be very carefull when implementing a database entries deletion as You could end up with empty database.
Secondly, always sanitize Your input to prevent SQL Injection.
Thirdly, learn PDO or at least mysqli_* functions instead of mysql_ as they are deprecated now and could be removed with any next PHP release.
Now, to Your problem, You are setting the ID values into a delete[] array value, that means You should do this:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . mysql_real_escape_string($id) . "'");
// do something with the $result here ...
}
Other option could be to expect only integers:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . (int)$id . "'");
// do something with the $result here ...
}

mysql database data into html table limiting column

My script is retrieving images from a database and displaying the images in a table. I want to have the table have 4 columns of images before it breaks the row and starts over. I've found some helpful answers on this forum but after re-organizing and fussing with the code it displays every image in it's own table rather than adding the row breaks after every fourth image. I'm running on little sleep, but hopefully a second pair of eyes could help me spot the problem.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$albumid'");
$i = 0;
echo "<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
echo "<td><a href='viewphoto.php?photo=$id'><img src='$thumbnail'>
</a></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "</tr><tr>";
}
echo "</table> </center>";
?>
Fiddled around a little bit and
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "<td><a href='viewphoto.php?photo=$id' rel='facebox'><img src='$thumbnail'>
</a></td>";}
worked like a charm.
The problem is that you are declaring your table inside the while loop. You should open and close your table tags on either side of the while loop, and only have tr and td's inside the loop.
There seem to be a couple of interchanged variable names here too that would cause unexpected behaviour. In your SQL query I think you mean ...albumid='$albumid'... and in the while loop I think you want while($row = mysql_fetch_assoc($pic)) {
Also, you should take note that this SQL query is open to SQL injection attacks
$i was initialized inside the loop. and Table also bring outside.
see the code below.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$pic'");
$i = 0;
echo "
<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($image)){
$id = $row["id"];
$thumb = $row["thumb"];
$date = strftime("%b %d, %Y", strtotime($row['date']));
echo "<td><img src='$thumbnail'></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
}
echo "</table> </center>";
?>

Deleting a record/multiple records with a checkbox(PHP/MYSQL)

Please can someone help me with this. I'm a total noob with php/mysql/stackoverflow.
I'm trying to delete a record from a mysql database - this is my code so far....
//Includes db connect file
// Display the student(s) within the html table
while($row = mysql_fetch_array($result))
{
echo "<tr><td align='centre' bgcolor='#693'><input name='checkbox[]' type='checkbox' id='checkbox[]' value=' $rows'Delete record?'>";
echo "<td> $row[studentid] </td> <td> $row[password] </td>";
echo "<td> $row[dob] </td><td> $row[firstname] </td>";
echo "<td> $row[lastname] </td><td> $row[house] </td>";
echo "<td> $row[town] </td><td> $row[county] </td>";
echo "<td> $row[country] </td><td> $row[postcode] </td>";
}echo "</table>";
echo "<tr><td colspan='11' align='center' bgcolor='#FFFFFF'><input name='delete' type='submit' id='delete' value='Delete selected student(s)'></td>";
echo "</tr>";
?>
<?php
if($_POST['delete']) // from button name="delete"
{
$checkbox = $_POST['checked'];
$countCheck = count($_POST['checked']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM student WHERE = $del_id";
$result = mysql_query($sql);
}
}
?>
$sql = "DELETE FROM student WHERE = $del_id";
WHERE <something> = $del_id, you're missing the <something>, which presumably should be id.
Also, you probably want to research "SQL Injection", "Prepared Statements" and "Input Sanitization", since your code is currently not sanitizing inputs/outputs or protecting against SQL injection.
$sql = "DELETE FROM student WHERE id= %d";
$sql = sprintf($sql,(int)$del_id);
$result = mysql_query($sql);
Now that should work, unless you have other errors
A couple of things to note:
Your delete should before before the output. I say this because even if a delete is successful, it will show up once more before the delete actually triggers, leaving you with a "Ghost" entry.
Make sure to sanitize the input from a user when dealing with a database--mysql_real_escape_string has a specific purpose, especially if you're not using an ADO. Alternatively you can use something like $delete_id = (int)$checkbox[$i] to make sure it's an integer value.
Your delete needs to reference which column in your where clause the delete pertains to. Usually this is the primary key of the table. Make sure to change the checkbox's value to something like $row['id'] (or whatever the key) and then re-reference that column in your DELETE FROM student WHERE <column> = <checkbox_value>)
LIVE DEMO
if(isset($_POST['delete']))
{
$check=$_POST['check'];
$count=count($check);
for($i=0;$i<$count;$i++){
$del_id = $check[$i];
$delete=mysql_query("delete from emp where id='$del_id'") or die(mysql_error());
}
if($delete){ $msg2="Successfully Deleted!!";}
}

Categories