Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
Related
Edit 3: I figured I should try to word, not only my issue but also my end goal better... so here it goes. I need data to be returned to the user by their input. What they put into the form, will return specific data from the database or nothing at all. The database I'm using is information on field reps. When the user enters into the form, they will be looking for specific information. The number they will be asked for will be the repID number. Now... the problem I am having is taking the number that is put into the form, and calling that specific data from the database. The user will not be able to see other data, not associated with other repID's.
Okay, I'm pretty sure I'm not supposed to just delete my entire initial post, but I'm still searching for an answer. Now, I would assume it should be relatively simple, however it has turned out to more taxing than I had originally thought. Perhaps I am not explaining my needs clear enough, I do tend to have that issue a lot.
Here it goes... How to Run sql Query with button click 2.0:
I have a database written in sql and stored on a server. The table I will be accessing is called dataRep and houses Rep Data. This data is user input via form submission. Upon coming to the website there is an option to "View Rep Information" by submitting the Rep's ID that was given. That Rep ID will be the auto increment repID from the table. Upon clicking the button, it opens a new window that should display the rep's data. It does not, however.
Here is the html the user will see:
<div class="pop_box">
<a class="rms-button" href="#popup1">Enter Rep Number Here</a> </div>
<div id="popup1" class="overlay">
<div class="popup">
<a class="close" href="#">×</a>
<div align="center"><br>
<br>
<p>Enter rep number in box below. Submission will open new window.</p>
<form method="get" action="/data/repPrepare.php" target="_blank" >
<input type="text" id="repSelect" name="repSelect" placeholder="Enter Rep Number Given Here" />
<button type="submit" class="newbutton">VIEW</button>
</form>
</div>
</div>
...changed the php a little, but now I get this error:
"Warning: mysqli_query() expects at least 2 parameters, 1 given on line 21
Unable to prepare statement: Query was empty"
<?php
$host = 'mhhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$con = mysqli_connect($host,$user,$pass, $db);
//-------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$query = mysqli_query("SELECT * FROM dataRep WHERE repID = ?"); //query
$stmt = mysqli_prepare($con, $query)
or die("Unable to prepare statement: " . $con->error);
$stmt->bind_param("i", $_GET["repSelect"]);
$stmt->execute();
$array = mysqli_fetch_row($result); //fetch result
//-------------------------------------------------------------------------
// 3) echo result as json
//-------------------------------------------------------------------------
echo json_encode($array);
?>
I would like to apologize in advance if I'm totally messing up the procedure for the forum, its just I am truly stuck and have been dealing with this issue for two weeks. Once again, I would appreciate any assistance that can be provided. I just need the php to pull the data tied the repID that the user puts in the box (repSelect).
try like this. You have to print variables bind in bind_result().So
<?php
$stmt = $mysqli->prepare("SELECT repID, RepName, RepBio, RepCerts FROM dataRep WHERE repID = ?");
$stmt->bind_param('i', $_GET['repSelect']);
$stmt->execute();
$stmt->bind_result($repID, $repName,$repBio,$repCerts);
while($stmt->fetch()){
echo $repName;//now it prints RepName
};
$stmt->close();
?>
i need an help from you all.
i had created an form using PHP. it's a school application registration form. it has one page only.
i need to generate registration number(session id used as registration number here) for everyone who opens the form.
instead of creating a session i have used ID for all. that is when some one submits the form, it checks the DB and if the registration number is there, it will increment one value and add the current form to DB.
my code here
<td>Application No : <input type="hidden" name="disablusr_dummyid" autocomplete="off" style="background:#f0efed;" value="00<?php
include('config.php');
$q="select MAX(auto_gen_id) from application_form";
$result=mysql_query($q);
$data=mysql_fetch_array($result);
$max_val=$data[0];
echo $max_val+1;
?>"/>
<input type="hidden" name="applicant_id" autocomplete="off" value="00<?php
include('config.php');
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
echo $erfdqwe+1;
?>" />
<input type="hidden" name="txt_applicant_id" style="display:none;" autocomplete="off" value="<?php
include('config.php');
$werqw = "select MAX(auto_gen_id) from application_form";
$resultghasw = mysql_query($werqw);
$dataqsax = mysql_fetch_array($resultghasw);
$erfdqweqti = $dataqsax[0];
echo $erfdqweqti+1;
?>" /></td>
but what is happening is when multiple users are using the form same session ID is generated and only one user is able to save the form and it reflects in DB. other forms are being not submitted and not added to DB.
help me in this error.. thanks in advance.
The solution here is not the use the hidden fields for the IDs :
At this moment u have something like this :
"INSERT INTO (id, ..., ...) VALUES('".addslashes($_POST['applicant_id']."', ...)
You should refactor your logic to calculate the id afterwards meaning that u drop the hidden fields and do this :
<?php
if (!empty($_POST)) {
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
$new_applicant_id = $erfdqwe+1;
}
And then use the $new_applicant_id into the INSERT sql.
On a sidenote your code is vulnerable for SQL injection and is using outdated functions.
You should try to move to mysqli or PDO and preferable use prepared statements
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.
I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).