Database doesn't Update - PHP Form through MySQLi - php

I'm currently trying to get a database updated through a PHP form. Firstly I get all the information from the database within the form, and then trying to update details within that form to reflect on the database.
I could successfully managed to get all the details from the database within the form but unfortunately doesn't update for that reason.
Here is the code to retrieve the info from DB, within the form which works 100%:
include_once 'db_connect.php';
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form id=updateVehicle action='' method=post";
echo "<div id='vehicleDescription'>";
echo "<div>";
echo "<label for=vin>VIN</label>";
echo "<input type=text id=vin name=vin minlength=17 maxlength=17 placeholder=e.g. BMW1234567890ABCD value=" . $row['vin'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<label for=make>Make</label>";
echo "<input type=text id=make name=make minlength=3 maxlength=13 placeholder=e.g. BMW value=" . $row['make'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<label for=model>Model</label>";
echo "<input type=text id=model name=model minlength=2 maxlength=15 placeholder=e.g. 530D value=" . $row['model'] . " />";
echo "<br/>";
echo "</div>";
echo "<div>";
echo "<input type=text name=id value=" . $row['id'] . " />";
echo "</div>";
echo "<span><?php echo $errorMessage;?></span>";
echo "</div> <!--End of vehicleDescription div-->";
echo "<input type='submit' class='submit' value='Update Ads' />";
echo "</form>";
}
}
The action is empty because it submits to itself, I've tried to use "echo htmlspecialchars($_SERVER["PHP_SELF"]);" but it didn't work, so I left it out.
Here is the code to process the update which doesn't work:
if(isset($_POST['vin'], $_POST['make'], $_POST['model'])) {
$vin = filter_input(INPUT_POST, 'vin', FILTER_SANITIZE_STRING);
$make = filter_input(INPUT_POST, 'make', FILTER_SANITIZE_STRING);
$model = filter_input(INPUT_POST, 'model', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
if($insert_stmt = $mysqli->prepare("UPDATE vehicles SET (vin=?, make=?, model=? WHERE id=? ")) {
$insert_stmt->bind_param("sssi", $vin, $make, $model, $id);
if(!$insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: UPDATE');
$mysqli->close();
}
}
header('Location: ../includes/register_success.php');
$mysqli->close();
}
For some unknown reasons to me, it doesn't update the database at all. The 'db_connect.php' works 100% as I'm using it for other database queries.
I'd really appreciate any help if you could point me in the right direction.
Thank you!

Aren't you getting an error when executing the update query? I can see an extra ( after SET in:
UPDATE vehicles SET (vin=?, make=?, model=? WHERE id=?
This should cause the query to fail which is a good reason why things are not updated in the database.

Related

Update Specific row textarea and mysql

I am working on Simple Admin Panel,
The method i am working on is to select the data from database and put it into textarea and behind the textarea update button,
when i update the textarea click update to execute query to update the table
but when i click update at the first row for example it execute the third row only even if i clicked the first row update button " picture attached "
<?php
include 'config.php';
echo '<link rel="stylesheet" href="style.css"type="text/css">';
$result = mysql_query("SELECT * FROM English");
while($row = mysql_fetch_array($result))
{
echo "<form action='' method='post'>";
echo "<table>";
echo "<tr>";
echo "<td><textarea rows='1' cols='1' name='txtid' readonly style='overflow:auto;resize:none'>" . $row['ID'] . "</textarea></td>";
echo "<td><textarea rows='4' cols='50' name='txtarea'>" . $row['Content'] . "</textarea></td>";
echo "<td><input type='submit' name='button' value='Update!'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
if(isset($_POST['button'])){
$textarea =$_POST['txtarea'];
$id = $_POST['txtid'];
$sql = "UPDATE English SET Content='".$textarea."' WHERE ID='".$id."'";
echo $textarea; echo $id;
mysql_query( $sql, $conn );
}
mysql_close($conn);
?>
Example
Well,
Changed the location for closing braces
to be after
echo "</table>";
echo "</form>";
it fixed the problem

Delete individual lines/rows with PHP button

What I am trying to do is have a PHP page display the contents of a MySQL database and and each line it displays, it give me a delete button so I can delete individual rows. I have the code kind of working. The code delete the lines of code, but not the one I select, instead it deletes the last line and not the one I tell it to delete.
Here is a screenshot, I know it does not look pretty, I was going to clean it up after I get the code working.
HTML:
<?php
// Delete php code
if(isset($_POST['delete_series']))
{
// here comes your delete query: use $_POST['deleteItem'] as your id
$delete = $_POST['delete_series'];
$delete_sql = "DELETE FROM `Dropdown_Series` where `id` = '$delete'";
if(mysql_query($delete_sql, $conn))
{
echo "Row Deleted </br>";
echo "$delete";
};
}
//Insert Code
if(isset($_POST['add_series']))
{
$insert_sql = "INSERT INTO dropdown_series (series) VALUES ('$_POST[add_series]' )";
if(!mysql_query($insert_sql, $conn))
{
die ('Error: ' . mysql_error());
}
echo "Series Added <br><br>";
}
?>
<br />
<h1>Add New Series Title</h1>
<h3>Add New: </h3><br />
<form name = action="add_series.php" method="POST">
<input type = "text" name = "add_series" required/><br /><br />
<input type ="submit" name="submit" value="Add">
</form>
<h3>Current Series: </h3><br />
<?php
//Delete button on each result of the rows
$query = mysql_query("SELECT id, series FROM Dropdown_Series"); // Run your query
// Loop through the query results, outputing the options one by one
echo "<form action='' method='POST'>";
while ($row = mysql_fetch_array($query))
{
echo $row['series'] . " ";
echo $row['id'];
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
//echo $row['series'] . " ". $row['id'] . "<input type='submit' value='delete'>";
echo "<br />";
}
echo "</form>";
?>
Your loop will result in multiple delete_series inputs - within the same form.
You could create separat forms for each option:
while ($row = mysql_fetch_array($query))
{
echo "<form action='' method='POST'>";
// ...
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
// ...
echo "</form>";
}
I believe that a very quick answer would be
while ($row = mysql_fetch_array($query))
{
echo "<form action='' method='POST'>";
echo $row['series'] . " ";
echo $row['id'];
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
//echo $row['series'] . " ". $row['id'] . "<input type='submit' value='delete'>";
echo "<br />";
echo "</form>";
}
If I were you I would prefer injecting some javascript in the logic, and perform the Delete request using an ajax call.
you can refer to this tutorial to get more understanding of what I am refering to https://scotch.io/tutorials/submitting-ajax-forms-with-jquery

Trying to create an editable HTML table using PHP and mySQL but the table won't update

I'm trying to make a HTML table as a frontend to a mySQL database. The table displays fine and I can type in the edits I want to make to each row of the table but when I press the submit button the changes aren't actually made. Can anyone see where I'm going wrong?
<?php
include("db.php");
$sql = "SELECT * FROM `artist`";
$result = mysqli_query($conn, $sql);
if (isset($_POST['update'])){
$artID = $_POST['artID'];
$artName = $_POST['artName'];
$key = $_POST['hidden'];
$UpdateQuery = "UPDATE `artist` SET `artID` = '$artID', `artName` = '$artName' WHERE `artist`.`artID` = '$key'";
mysqli_query($conn,$UpdateQuery);
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
};
echo "<table border='1'>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "</tr>";
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The db.php file simply includes the connection info to the mySQL database and I'm 100% sure there's nothing wrong with it as it retrieves the table correctly it just doesn't update.
You are putting form tag inside tr which is not allowed td are only allowed
so you have to remove that tr from there.
You have to use jquery or you can replace the table with some other grid structure so that it can look the same and the form can be placed there as well
One more suggestion Don't mix the php and html together separate them for the clean code
If you do all these you code will be like this
Your form is being constructed with multiple elements with the same name. When you submit the form it is using the last elements as the values so regardless of the record you want updated the last record is being updated (or throwing an error because of string encapsulation). You should use parameterized queries as well.
So instead of:
if ($result->num_rows > 0) {
echo "<form id ='artisttable' action ='getartiststable.php' method ='post'>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" ."<input type='text' name ='artID' value ='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='text' name ='artName' value ='" . $row["artName"] . "' </td>";
echo "<td>" . "<input type = 'hidden' name ='hidden' value='" . $row['artID'] . "' </td>";
echo "<td>" . "<input type='submit' name ='update'" . " </td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Use:
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {?>
<form class='artisttable' action ='getartiststable.php' method ='post'>
<tr>
<td><input type='text' name ='artID' value ='<?php echo $row['artID'];?>' /></td>
<td><input type='text' name ='artName' value ='<?php echo $row["artName"];?>' /></td>
<td><input type = 'hidden' name ='hidden' value='<?php echo $row['artID'];?>' /></td>
<td><input type='submit' name ='update'" . " </td>
</tr>
</form>
<?php } ?>
</table>
So you get a form for each data set. Here's a link on prepared statements with mysqli: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. You also should update your mark up. Tables for formatting aren't the best approach. Your inputs also weren't closed missing >.
Also this changed artisttable from an id to class because there will be multiples. Update CSS/JS accordingly.

PHP Required fields (No HTML)

So I need help with a required form field. I want the 3 fields (exam_id, subject, exam_date) to be required fields when filling out the PHP form. So when the insert button is hit, if a field is left blank and error will display or the action won't complete unless every field is filled in.
I'm using all php, no HTML and no, I don't want to redo my form as HTML calling the php, I want it like this. There's no security problems either, this is just a simple project.
My code:
<?php
echo '<link rel="stylesheet" type="text/css" href="css/tables.css" />';
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("StudentExams", $con);
if (isset($_POST['update']))
{
$UpdateQuery = "UPDATE Exam SET exam_id='$_POST[exam_id]', subject='$_POST[subject]', exam_date='$_POST[exam_date]' WHERE exam_id='$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete']))
{
$DeleteQuery = "DELETE FROM Exam WHERE exam_id='$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
if (isset($_POST['insert']))
{
$InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('$_POST[uexam_id]','$_POST[usubject]','$_POST[uexam_date]')";
mysql_query($InsertQuery, $con);
};
$sql = "SELECT * FROM Exam";
$Data = mysql_query($sql,$con);
echo "<table id='size' border='1'>
<tr>
<th>Exam_ID</th>
<th>Subject</th>
<th>Exam_Date</th>
</tr>";
while($record = mysql_fetch_array($Data))
{
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=exam_id value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=text name=subject value=" . $record['subject'] . " </td>";
echo "<td>" . "<input type=text name=exam_date value=" . $record['exam_date'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['exam_id'] . " </td>";
echo "<td>" . "<input type=image name=update value=update id=submit src=images/update.png" . " </td>";
echo "<td>" . "<input type=image name=delete value=delete id=submit src=images/delete.png" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=examisud.php method=post>";
echo "<tr>";
echo "<td><input type=text name=uexam_id></td>";
echo "<td><input type=text name=usubject></td>";
echo "<td><input type=text name=uexam_date></td>";
echo "<td>" . "<input type=image name=insert value=insert id=submit src=images/insert.png" . " </td>";
echo "</form>";
echo "</table>";
echo "<a href='ExamForm.html'> Back to main page </a>";
mysql_close($con);
?>
Thanks in advance for anyone who can help me out! I feel there is either a very simple solution i'm missing or it's very convoluted due to the absence of a generic HTML form.
Just do a check on the top with isset
if(!isset($_POST['exam_id'],$_POST['subject'],$_POST['exam_date']))
{
echo "These fields are required ! Please fill it up";
header("location:backtoform.php");exit;
}
Warning : Since you are passing the $_POST parameters directly onto your query, you are prone to SQL Injection attacks.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
isset( ... ) is only used to see if a field is set or not. It doesn't care if the value of the field is empty.
You need to use empty( .. ) instead. It would return true only if the field was ever set and is not empty. Two apples with one shot.
Across all your if statements, use !empty. Maintain an $error variable and initialize it to FALSE. Whenever an error occurs, set $error to TRUE.
In the end, perform the required operation only when $error == FALSE.
$error = false;
if ( !empty($_POST['update'] ){
// stuff
}
else {
// display error message
$error=true;
}
if(!$error){
// operations
}
This way you can neatly separate validations from operations.

Post 'SELECT' Value To Next Page PHP

Here is the form code:
<?php
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT ID, NAME FROM b_sonet_group ORDER BY ID DESC");
echo "<form class='form-vertical login-form' action='step-2.php' method='POST'>";
echo "<h4 class='form-title'>Step One: Choose Your Project</h4><div class='control-group'><div class='controls'>";
echo "<select>";
echo "<option value=''>Choose Your Project</option>";
while($row = mysqli_fetch_array($result))
{
echo "<option name='ID' value='" . $row['ID'] . "'>" . $row['NAME'] . "</option>";
}
echo "</select>";
echo "</div></div>";
echo "<div class='form-actions'><button type='submit' name='submit' class='btn green pull-right'>Proceed to Step Two <i class='m-icon-swapright m-icon-white'></i></button></div></form>";
mysqli_close($con);
?>
What do I need to put on page 2 that retrieves the value ID from the form on the previous page and how do I print it so I can check it is the correct ID?
Simple I know but my brain has packed up and gone home.
You need to change your select to
echo "<select name=\"project\">";
On your second page you can get the value with
echo $_POST['project'];
You need to move the name from option to your select. Then echo $_POST['id'];

Categories