Inserting SQL Database values in HTML update form - php

I'm trying to make a form that will allow a user to edit records in the database.
My main.php is a table where the user can click on a record to edit / delete:
echo "<td>".$row["fname"].", ".$row["first_name"]."</center></td>";
echo "<td><center>".$row["gender"]."</center></td>";
echo "<td><center>".$row["city"]."</center></td>";
echo "<td><center>".$row["extra"]."</center></td>";
echo '<td><center><img src="edit_icon.png"/><center></td>';
echo '<td><center><img src="delete.gif"/><center></td>';
echo "</tr>";
}
?>
<input type="hidden" name="p_ID" value="<?php echo $row["p_ID"]?>"></input>
<input type="hidden" name="lname" value="<?php echo $row["lname"]?>"></input>
etc..
When the user clicks the edit icon, it redirects to the form page where I need the values ($row['fname']) to show up in their respective fields. I've tried suggested solutions but I still don't know how to accomplish this correctly. I keep getting errors. This is what I've tried with my form.php
#$submit=$_POST['submit'];
#$lname=$_GET['lname'];
#$gender=$_GET['gender'];
#$city=$_GET['city'];
#$extra=$_GET['extra'];
?>
Last name <input type="text" name="lname" value= <?php echo $lname ?>><br><br>
Gender <input type="radio" name="gender" value="M" <?php if($gender=="M") {echo "checked";} else {echo " ";} ?>/>M
<input type="radio" name="gender" value="F" <?php if($gender=="F") {echo "checked";} else {echo " ";} ?>/>F<br><br>
City <select name="city">
<option value="x">Select</option>
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
$num_results=mysql_num_rows($result);
mysql_close($db);
for ($i=0;$i<$num_results;$i++)
{
$row=mysql_fetch_array($result);
echo"<option value='".$row['city_id']."'", $row['city_id']==$row['city_ID']? " selected='selected'" : '',">".$row['city']."</option>";
}
?>
</select><br><br>
Extra <input type="checkbox" name="extra" value="yes" <?php if($extra=="yes") {echo "checked";} else {echo " ";} ?>/><br><br>
And I'm not really concerned with any SQL injections or anything right now, I just need this working. I'd be grateful for any help!
Errors: Undefined index for everything

You are closing the connection before mysql_query is used in mysql_fetch_array.
You are trying to fetch the rows incorrectly.
mysql_close isn't needed unless you have a lot of processing after the query because the connection is closed after the script has finished running anyway.
Also, declare your variables like this to remove the undefined index errors:
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
Note: this also protects against sql injection but mysql_real_escape_string() will only work after you connect.
<?php
$db=mysql_connect("localhost","root") or die('Not connected : ' . mysql_error());
mysql_select_db("my_db",$db) or die (mysql_error());
$submit = isset($_POST['submit']) ? mysql_real_escape_string($_POST['submit']) : "";
//other vars here
$SQL="SELECT * FROM cities";
$result=mysql_query($SQL) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['city_id']."'>".$row['city']."</option>";
}
mysql_close(); // now you can close the connection
?>

What you need is form submission check. Here is the general form of a single-page update script:
<?php
if(isset($_POST['submit'])) {
// Form was submitted, process it and display message
exit(); // Prevent form from being displayed again
}
?>
<!doctype html>
<html>
<body>
<form method="POST" action="form.php">
<!-- fields -->
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Related

PHP if/else statement acting weird

I'm relativity new to php and just testing out some code. The odd thing is that the code both does/doesn't work. The code should check a MySQLi database to determine the state of the check box and then apply that state to the checkbox. What the code currently does is designate the checkbox state based solely off the value of the if condition, regardless of the MySQLi database values.
Here is the code for the html page, it's the if statement near the bottom that's causing issues;
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$results = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
$sql_2 = mysqli_query($conn, "SELECT state FROM test2 WHERE id = '0'") or die('Error getting data.');
if ($sql_2 == "0") {
echo "checked";
} else {
echo " ";
}
mysqli_close($conn);
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1" checked> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset<br>
</body>
</html>
The odd thing about this code is that the if ($sql_2 == "0") results in the checkbox remaining unchecked, but changing the 0 to a 1, if ($sql_2 == "1") results in the checkbox remaining checked. Both results are regardless of what the database shows.
I know all the other bits of code work, because when I check the checkbox and submit, it updates the database and displays it correctly (the reverse is also true).
If anyone knows why if ($sql_2 == "0") is not working, please let me know. I've even checked other stack overflow postings, and as far as I can tell, everything should be coded properly.
Edit:
I should have stated that in the above question, changing the = to == or reversing the order doesn't fix the problem. The if statement still only returns the else statement.
I've done additional research and think that the issue is related to the use of mysqli_query to retrieve the data, as it should likely be mysqli_fetch_row.
if ($sql_2 = "0") will make the value of $sql2 to '0' and this condition will be always true
change it to
if ($sql_2 == "0")
to prevent the accidental assignment you can do like below
if ("0"==$sql_2)
ISSUE FIXED
The solution was to add a mysqli_data_seek() to the php, below is the working code.
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$result_1 = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($result_1, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
$query_1 = "SELECT state, id FROM test2 ORDER BY id";
$sql_3 = mysqli_query($conn, $query_1) or die('Error getting data.');
if ($result_2 = $sql_3) {
mysqli_data_seek($result_2, 0);
$row_1 = mysqli_fetch_row($result_2);
}
if ($result_3 = $sql_3) {
mysqli_data_seek($result_3, 1);
$row_2 = mysqli_fetch_row($result_3);
}
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
if ($row_1[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1"
<?php
if ($row_2[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset
<br>
<?php
mysqli_close($conn);
?>
</body>
</html>

Update a MySQL Database with a Form

I'm trying to create a form that allows a user to select a field from a drop down box and then change what is currently written in the field.
My current code allows me to view the drop down list select the field I want to change and then enter my new text into a box. But when I click update, nothing happens.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT * FROM news_updates";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['Text'];
$i++;
}
$total_elmt=count($roll);
?>
---------------------------------------------------------Now I have the form
<form method="POST" action="">
Select the news post to Update: <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
Text Field: <input name="username" type="text" /><br />
<input name="submit" type="submit" value="Update"/><br />
<input name="reset" type="reset" value="Reset"/>
</form>
-----------------------------------------------Now I have the update php
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Well, you seem to be missing the $value part. Something like this should do, for the last part:
<?php
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$value = mysql_real_escape_string($_POST['sel']);
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
echo $query2; //For test, to see what is generated, and sent to database
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Also, you should not use mysql_* functions as they are deprecated. You should switch to mysqli or PDO.
First, try adding a value to your options, like so:
for($j=0;$j<$total_elmt;$j++)
{
?>
<option value="<?php echo $roll['id']; ?>"><?php echo $roll['option_name']; ?></option>
<?php
}
Then, when you parse your file, go like so:
$value = $_POST['sel']; // add any desired security here
That should do it for you
You need to change this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
to this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option value="<?php echo $roll[$j];?>"> <?php echo $roll[$j];?></option> <?php
}
And you also need to change the update query from this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
to this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='".$_POST['sel']."'";
N. B.: Here I am assuming that $_POST['sel'] has the value selected by the user from the drop down menu because I could not find anything which corresponds to $value

PHP put data from database into form

I'm relatively new to PHP and have been working on a basic survey as a practice project.
The user logs in, answers the questions and the data is sent to the database. So far so good.
However, since the only thing that the login is set up for is to do the survey, I want them to be able to go back and change their answers at any time.
I've set it up so that it checks if the user has already filled in the info on the database, and edits values rather than adding new row if they've filled it in before.
However, I now want them to be able to see the choices that they made and edit them.
I know how to get the data back and echo it to the page, what I don't know how to do is get it to display the form with the default values set at the users previous selections.
Apologies for any display problems, its being a bit erratic!
so for example:
<?php if(!isset($_SESSION['username'])){
// are logged in
header("location:login.php");
} ?>
<form name="questionnaire" action="submit_survey.php" method="post">
<input name="Q1" type="radio" method="post" value="1">1
<input name="Q1" type="radio" method="post" value="2">2
<input name="Q1" type="radio" method="post" value="3">3
<input name="Q1" type="radio" method="post" value="4">4
<input name="Q2" type="radio" method="post" value="1">1
<input name="Q2" type="radio" method="post" value="2">2
<input name="Q2" type="radio" method="post" value="3">3
<input name="Q2" type="radio" method="post" value="4">4
</form>
PHP sending to database:
include('db_login2.php');
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
if(mysqli_connect_errno($con)) {
echo "failed to connect" . mysql_connect_error();
}else {
$username = $_SESSION['username'];
//Question 1.1
$Q1 = $_POST['Q1'];
$Q2 = $_POST['Q2'];
//INJECTION PREVENTION (Not shown)
$resulting = mysqli_query($con, "SELECT username FROM users WHERE username='$username'");
$counting = mysqli_num_rows($resulting);
if($counting != 0){
mysqli_query($con,"UPDATE users SET Public_Services='$Q1', Politicians='$Q2'
WHERE username='$username'");
$_SESSION['completed'] = true;
header("location:login.php");
mysqli_close($con);
} else {
$sql= "INSERT INTO users(username, Public_Services, Politicians)
VALUES ('$username','$Q1', '$Q2')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//if it works
$_SESSION['completed'] = true;
header("location:loggedin.php");
mysqli_close($con);
}
}
?>
PHP for getting data back from database
include('db_login2.php');
$con = mysqli_connect("$host", "$username", "$password", "$db_name");
if(mysqli_connect_errno($con)) {
echo "failed to connect" . mysql_connect_error();
}else {
$username = $_SESSION['username'];
$result = mysqli_query($con,"SELECT * FROM users WHERE username='$username'");
echo $row = mysqli_fetch_array($result);
mysqli_close($con);
}
?>
I was wondering if it was possible to do something like having inline php in the html form which comes to life depending on the value of the user's original selection.
Any thoughts?
Thanks for any help!
To populate the survey with the users previous answers, you would us the $row = mysqli_fetch_array($result);
<?php
... // all your other code
$row = mysqli_fetch_array($result);
?>
<form name="questionnaire" action="submit_survey.php" method="post">
<input name="Q1" type="radio" value="1" <?php if($row['Public_Services'] == 1) echo 'checked="checked"'?>>1
<input name="Q1" type="radio" value="2" <?php if($row['Public_Services'] == 2) echo 'checked="checked"'?>>2
<input name="Q1" type="radio" value="3" <?php if($row['Public_Services'] == 3) echo 'checked="checked"'?>>3
<input name="Q1" type="radio" value="4" <?php if($row['Public_Services'] == 4) echo 'checked="checked"'?>>4
<input name="Q2" type="radio" value="1" <?php if($row['Politicians'] == 1) echo 'checked="checked"'?>>1
<input name="Q2" type="radio" value="2" <?php if($row['Politicians'] == 2) echo 'checked="checked"'?>>2
<input name="Q2" type="radio" value="3" <?php if($row['Politicians'] == 3) echo 'checked="checked"'?>>3
<input name="Q2" type="radio" value="4" <?php if($row['Politicians'] == 4) echo 'checked="checked"'?>>4
</form>
or using a php for loop
<?php
... // all your other code
$row = mysqli_fetch_array($result);
echo '<form name="questionnaire" action="submit_survey.php" method="post">';
for($i=1;$i<=4;$i++){
echo '<input name="Q1" type="radio" value="'.$i.'"';
if($row['Public_Services'] == $i) echo 'checked="checked"';
echo " />".$i."<br />\n";
}
echo "<br />\n";
for($i=1;$i<=4;$i++){
echo '<input name="Q2" type="radio" value="'.$i.'"';
if($row['Politicians'] == $i) echo 'checked="checked"';
echo " />".$i."<br />\n";
}
echo "</form>";
?>
You could either output the form's results as values in the HTML itself, or you could create a small Javascript snippet via PHP that will set the appropriate values once the form is loaded. The second method is much cleaner, but your clients will need to support Javascript for this to work. This isn't usually a problem, unless they've explicitly disabled Javascript, in which case the page just won't show the form data.
Using jQuery, you could do something like:
$(function() {
<?php
if (isset($foo)) { // foo is a value from your database
echo '$("#fooField").val("' . $foo . '")';
}
// ....more fields here
?>
}
Thus, the aforementioned code will output a jQuery code on load which will set the appropriate values for all of the form elements
You can have tags inside the html and echo the form based on the values.
Or you simply echo every line.
Edit: You might have a look at this: http://php.net/manual/en/control-structures.alternative-syntax.php

Php Undefined index, when storing a variable

Problem: Need to store field value when doing this query on my database. Have a couple pages that's using this same syntax but for some odd reason this isn't cooperating..
HTML
<form method="post" action="listPage.php">
<fieldset>
<legend>Pull some data</legend>
<label for="name">Name</label>
<input type="text" name="name" id="name" maxlength="255" />
<hr />
<br />
<input type="submit" value="find event" />
</fieldset>
</form>
listPage.php
<?php
//CONNECT TO DATABASE
$user="root";
$password="";
$database="db";
$connection=mysql_connect('localhost',$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "NOT running...";
//STORE ALL DATA FROM PREVIOUS FORM
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
echo "running...";
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
mysql_close($connection);
?>
Check to see if the post value is set before doing anything with it. (Also, don't forget to call mysql_real_escape_string() on it).
It may not be set if this code occurs on the page when it initially loads or is refreshed after having data posted to it.
// Don't attempt any of this unless you actually have a $_POST value
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
I couldn't quickly find any documentation regarding possible reserved words for POST or html form variables, so I went to
http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_form_method_post
and changed fname field to name, (clicked edit and click me button) and the POST variable was not passed or recognized.
So you might consider changing the name of your field to something other than name.

Simple PHP task of updating database with radio buttons

Front-end designer here, not a PHP developer and I really need the help. Need to make a system that will allow the client to log into their own area to update a table. The table will have about 20 records and each row will be edited with radio buttons (4 choices). Only 2 columns, one for ID and one called status (the editable data).
The viewer will only see the changes made by the client and a background color change to that row depending on the status, which means the editable part will have to hold 2 pieces of data (integer value to change color and the name of the status, e.g. value of the radio button to change color, and label of button to echo the text into the cell). Will deal about login system later...
Database set-up:
Database: test
Table: fire_alert
Structure:
id (INT, PRIMARY); color(INT); warning(VACHAR);
connect.php:
<?php
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'test';
// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die("Could not connect to server ... \n" . mysql_error());
mysql_select_db($db)
or die("Could not connect to database ... \n" . mysql_error());
?>
view.php:
<div id="container">
<?php
// connect to the database
include('connect.php');
include("header.php");
// get results from database
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
// display data in table
echo "<table>";
echo "<tr> <th>Area</th> <th>Status</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($result)) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['warning'] . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
echo '<td>Change Area Status</td>';
?>
</div>
<body>
</body>
</html>
edit.php (client access only) no dynamic data changes yet, hardcoded HTML so far:
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="container" class="edit">
<div id="radio1">
<?
$result = mysql_query("SELECT * FROM fire_alert")
or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "<br /><br />";
?>
<table class="edit">
<tr><th>Area</th><th>Status</th></tr>
<tr>
<td>1</td>
<td>
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" /><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" /><label for="radio4">Closed</label>
</form>
</td>
</tr>
</table>
</div>
<?php echo '<td>Update</td>'; ?>
</div>
The simplest way to run this update (or the way I use anyways) is by leveraging javascript. Have each section of radio blocks in its own form that submits automatically onChange, and include a hidden variable to indicate page submission. Then just write a function to update the database, based on the inputted user's id (or however you're validating) and their selection choice...
Something like:
if($_POST["submit"] == 1)
{
$id = $_POST["id"];
$radio = $_POST["radio"];
$query = "UPDATE fire_alert SET warning = '$radio' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
}
You have a problem with how you formatted your view.php link, that line should be as follows:
'Update'; ?>'
Though the above won't quite work as you're intending since it's not submitting the form, so the radio button values won't be passed... instead you should do:
<form method="post" action="edit.php">
<input type="radio" id="radio1" name="radio" value="1" onChange="this.submit()"/><label for="radio1">Safe</label>
<input type="radio" id="radio2" name="radio" value="2" onChange="this.submit()"/><label for="radio2">Caution L1</label>
<input type="radio" id="radio3" name="radio" value="3" onChange="this.submit()" /><label for="radio3">Caution L2</label>
<input type="radio" id="radio4" name="radio" value="4" onChange="this.submit()"/><label for="radio4">Closed</label>
<input type="hidden" name="id" value="<?=$row["id"]?>" />
</form>
And you'll need to edit your php to reflect that difference as well

Categories