I have a confusion in mind regarding a logic.. it is a form that i first want to validate then I want to save in database and then i want to display it on another page.
I have validated it (transferring (i.e. form action) the form to the same page), I have saved it in database, and now I m trying to display the data on another page.
What I have thought, that I'll save the data to the db and transfer some unique value to another page, maybe some sort of number auto generated by database related to the same form.
now I have problem how to do it? Any ideas guys?
Since it is a logic hence I am tagging php, MySQL and JS
Call mysql_insert_id() once you perform INSERT operation something like this,
$lastInsertedId = mysql_insert_id(); # Assuming you have an auto increment column in your table.
header('Location: view.php?id='.$lastInsertedId);
Than in your view.php get the id & fetch record to display it,
$id = $_GET['id'];
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
After insertion query,use
$lastID = mysql_insert_id();
After then you can redirect to another page like,
header("location:view_page.php?id=$lastID");
Than in view_page.php page,use
$lastID= $_GET['id'];
after then fetch record from database to display data.
NOTE: It will work only when your database table has autoincremented field as index key.
Using mysql_insert_id() is a way. But If you do not want to query your database and still have that then you can do it this way . Below goes the example
<form name="frm" method="POST" action="display.php">
<input type="text" name="your_name" value="" />
<input type="text" name="age" value="" />
<input type="submit" name="save" value="Save" />
</form>
Now in your display.php page
<?php
// DO YOUR DATABASE CONNECTIVITY
$name = $_POST['your_name'];
$age = $_POST['age'];
$query = "insert into table_name values('$name','$age')";
if(mysql_query($insert)) {
?>
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td><?php echo $name;?></td>
<td><?php echo $age;?></td>
</tr>
</table>
<?php } else { echo "No Insertion"; } ?>
Remember mysql_* function are depreciated. So avoid those. Also check for sql injection
Related
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
It may be a minor error but I am currently trying to post from a html form into the database to add a new entry.
Here is the code:
<div>
<?php
$menu = "INSERT INTO content (id, path, name)
**VALUES ('".$_POST['id']."', '".$_POST['path']."', '".$_POST['name']."')";**
if ($connnect->query($menu) === TRUE) {
echo "New page added successfully";
} else {
echo "Error";
}
?>
<form action="" method="post" name="menus" id="menus">
<table style="width: 500px;">
<tbody>
<tr>
<td>
<textarea name="id" id="id"></textarea>
</td>
</tr>
<tr>
<td>
<textarea name="path" id="path"></textarea>
</td>
</tr>
<tr>
<td>
<textarea name="name" id="name"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="button" id="button" value="Upload">
</td>
</tr>
</tbody>
</table>
</form>
</div>
However obviously you cannot put each $_POST from the form into each value is there another way to do this or can someone help me?
Kind Regards,
Lewis
use sprintf which can make it a bit more readable in the order of the parameters passed to the values:
$menu = sprintf("INSERT INTO content (id, path, name) VALUES ('%s', '%s', '%s')", mysql_real_escape_string($_POST['id']), mysql_real_escape_string($_POST['path']), mysql_real_escape_string($_POST['name']));
Considering this is your full code, one major problem is that you are inserting the form contents every time the page is loaded. If your form processing is in the same page, you may want to add a simple check. For example:
<?php
if (isset($_POST['submit'])) {
# form information received, process it
}
# else continue with your normal script and display the form
?>
In this case, in a first page load the $_POST data is not set so only the form will apear. When the form is submitted though, the script will detect there is data and process it.
And explained in the comments, PHP Data Objects (or PDO for short) is a much more modern, portable and safe way to deal with databases. There are plenty of explanations over the internet on how and why; and the manual page itself is pretty straight forward to read. You can prepare statements, and then the class itself will handle all the escaping needed to make your script secure. Quick example:
# make a connection
$db = new PDO(/* database info */);
# prepare your statement with the placeholders for your data
$st = $db->prepare("
INSERT INTO content (id, path, name)
VALUES (?,?,?)
");
# execute the query with the POST data
$success = $st->execute([
$_POST['id'],
$_POST['path'],
$_POST['name']
]);
if (!$success) {
# error ...
}
I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/
I have a value coming from another form in the same page called $_POST['serial']. And i want to use this value to run a query in another form but after I submit the second form nothing happened and the query not running.
<?php
if (isset($_POST['serial'])) {
$serial = $_POST['serial'];
?>
<form action="" method="post">
<button type="submit" name="submit">Click to use</button>
</form>
<?php
if (isset($_POST['submit'])) {
$query = mysql_query("UPDATE table_name SET status = 'inactive' WHERE serial = '$serial'");
}
}
?>
To pass the variable along you would create a hidden input on your second form to contain the value:
<?php
// check and clean up the passed variable
$serial = isset($_POST['serial']) ? htmlspecialchars($_POST['serial']) : '';
?>
<form action="" method="post">
<input type="hidden" name="serial" value="<?php echo $serial; ?>" />
<button type="submit" name="submit">Click to use</button>
</form>
For Safety's Sake
Your script is at risk for SQL Injection Attacks.
If you can, you should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really not hard.
Additional Thoughts
If you're planning to do a two-step form you'll likely want to place all of the data processing outside of the form page, in a separate PHP file. With the limited code that you have shown I fear that we will miss something in our answers which will lead you to additional questions because your code still isn't working as you would expect.
A button needs a name and a value to be successful. Your button doesn't have a value so $_POST['submit'] will be undefined.
Add a value attribute to your <button> element.
After you do that, $serial will be undefined because your form doesn't submit that.
You need to include it in your form too:
<input type="hidden" name="serial" value="<?php echo htmlspecialchars($serial); ?>">
I'm kinda new to PHP and MySQL.
<p>Pickup Date: <input type="date" name="date"></p>
<input type='submit' name='submit' value='Secure Order!'>
So I have his part in my code. I want the date to be saved in my database. In my database I have a table named date with columns 'date' and 'account name'. I want that when I click the 'secure order' button, the date in the textbox saves in the database. Also, the current user logged in would also be saved in account name.
on your form suppose you have:
<form id="myform" action="myphppage.php" method="post">
now when you hit submit the data in the input will be posted to myphppage.php.
Now you need to write myphppage.php.
At the top you will have something like:
<?php
$account = $_POST['account'];
$mydate = $_POST['date'];
$query="INSERT INTO date (date,account name) VALUES($mydate,$account)";
//Use mysqli object to execute query.
?>
I haven't used the mysqli library because I got used to using the old mysql_ libraries but I got yelled at for suggesting it since it is now deprecated.
This should get you started.
It is also common to have the form post back to itself with the data. In which imagine your form is on the page "myphppage.php" then you could have the following at the top:
<?php
if(isset($_POST['submit'])){
//continue with the php code from above here
}
?>
Why are you using double quotes on your first <input> and then simple quotes on your second <input>? Most of the time, in HTML, we will encourage the use of double quotes.
Also, there are a lot of missing parts for this form to be correct. Here is just an example of how to use the variable typed in the input:
<?php
if(isset($_POST['date'])) {
echo "You picked ", $_POST['date'], "\n"
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<p>Pickup Date: <input type="date" name="date"></p>
<input type="submit" value="Secure Order!">
</form>
As for the MySQL part, you will need to learn and try a bit by yourself. Start there: http://www.php.net/manual/en/book.mysqli.php
You can use PHP $_POST SuperGlobal to do that :
HTML:
<input type="text" name="username" />
PHP-onsubmit
<?php
if(isset($_POST['submit'])
{
$username= $_POST["username"];
$date= $_POST["date"];
// your insert code //
}
?>