Use $_GET together with $_POST - php

I'm trying to post a new record in a table with <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">. But every row in my table has an unique id, and that id is put next to every name. So I'm trying to get the id with $_GET but it's been unsuccesful so far. Is the method I'm trying wrong or am I doing something else wrong? If anybody can tell me what's going wrong, I'd appreciatie.
PHP that gets placed above <html>
<?php
if (isset($_POST['saveRecord'])) {
if (isset($_POST["newRecord"]) && !empty($_POST["newRecord"])) {
$id = $_GET['record'];
$klant=$_POST['newRecord'].$id;
$query = "INSERT INTO table2
(recordid, recordname)
VALUES
(NULL, '$record')";
mysqli_query($con, $query);
}
}
?>
Markup
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<?php
$query = ("select * from table1");
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row['rowid'];
?>
<tr>
<td>
<input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" />
<a href="?record=<?php echo $id; ?>">
<button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button>
</a>
</td>
</tr>
<?php } ?>
</table>
</form>

Don't bother trying to do both at once (the $_GET variables will only be passed if it is included in the action of the form).
The script won't pick up the the records from the $_POST as the names of the field have the ID included in them.
Either create each record as an individual form (move the whole lot inside the WHILE loop), or you could use the ID held within the field name, like this:
$newdata = array();
foreach($_POST as $k => $v) {
if ((substr($k,0,9) == 'newRecord') && (!empty($v)) {
$id = substr($k,9);
$klant = $v;
$newdata[$id] = $klant;
}
}
Which should extract the ID from the field name and associate it with the data entered to the form.

Your button name is
name="saveRecord<?php echo $id; ?>
SO this condition need $id
if (isset($_POST['saveRecord'])) {// your id missing

move your opening and closing form tags in while loop,it will submit only 1 form at a time,otherwise all the inputs will be submitted.

Related

How to input a number into a database based of a drop down menu consisting of data from another table in PHP?

I wish to input a number into a database based of a drop down menu consisting of data from another table.
Links table:
Category table:
So basically my drop down will consist of the category.cat written information. But when I submit the form it will input category.id into the links.catID column in the database.
The code I have so far is:
<?php
// since this form is used multiple times in this file, I have made it a
function that is easily reusable
function renderForm($links, $url, $catID, $type, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != ''){
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Link Title: *<br></strong> <input type="text" name="links" size="40" value="<?php echo $links; ?>" /><br><br/>
<strong>URL: *<br></strong> <input type="text" name="url" size="40" value="<?php echo $url; ?>" /><br><br/>
<?php
require 'db/connect.php';
echo" <strong>Category: *<br></strong>";
echo "<select name='catID' id='catID'>";
$sql = "SELECT * FROM links";
$results = $db->query($sql);
if($results->num_rows){
while($row = $results->fetch_object()){
echo "<option>";
echo "{$row->catID}";
echo "</option>";
}
} echo "</select><br>";
?>
<br>
<strong>Type: *<br></strong> <input type="text" name="type" size="40" value="<?php echo $type; ?>" /><br><br/>
<p>* Required</p><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])){
// get form data, making sure it is valid
$links = mysql_real_escape_string(htmlspecialchars($_POST['links']));
$url = mysql_real_escape_string(htmlspecialchars($_POST['url']));
$catID = mysql_real_escape_string(htmlspecialchars($_POST['catID']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
// check to make sure all fields are entered
if ($links == '' || $url == '' || $catID == '' || $type == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($links, $url, $catID, $type, $error);
} else {
// save the data to the database
mysql_query("INSERT links SET links='$links', url='$url', catID='$catID', type='$type'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','','','');
}
?>
Which gives me the following:
May be try this? (Considering the links.links columns and category.cat columns are common)
Store the value of dropdown in a variable say $dropdown_selected_option
Getting the id from the category table using sql:
$sql = "Select id from category where cat = '$dropdown_selected_option'";
$result = mysqli_query($conn, $sql);
Later run a query again to update the given fields in second table;
Update links set
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
// Run update query here where $row['id'] has the ID from the category table required.
}
}

Using $_GET outside the while loop in which [''] is defined

For example, I have the following code:
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC");
while ($row = mysqli_fetch_array($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// for each post a user has made, a new div will be echo's
echo "
<div class='message_wrapper'>
// all content here which displays the message and author.
// consider this anchor link, and see $_GET approach below.
<a href='/inc/del_post.php?id=$thought_id>'>Delete </a>
<div id='toggleComment$thought_id' class='new_comment'>
<form action='' method='post' enctype='multipart/form-data'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
</div>
</div>";
} // while loop closed
// sending comments to database
$comment = htmlentities(trim(strip_tags(#$_POST['comment_msg'])));
$comment = mysqli_real_escape_string($connect, $comment);
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
}
?>
Before, I had the 'send_comm' processing in the while loop, and when I use to submit the form, the comment would be added to all of a users posts. For example, Alice has made two posts, I add a comment to one, both posts will display that message (and two new rows in db).
Now, to fix the above issue, I have put the 'send_comm' processing, outside the while loop,but of course, with this $thought_id (which in in my INSERT) would be undefined. Also, having it outside the while loop provides no way of the comment knowing which thought_id is is assigned to. So to fix this, I tried to use $_GET:
$thought_id_from_anchor = $_GET ['id'];
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id_from_anchor')");
header ("Location: /profile_page/$user");
}
}
But of course, since it is outside the while loop, I get an undefined error on id.
I just need a comment to be added to the $thought_id it is being added to.
You can simply add a hidden input to your form containing the value of $thought_id:
<form action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='thought_id' value='$thought_id'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
Then when the form is submitted, you can access the value of thought_id using $_POST for your query (also cleaned it up a bit):
// if button is pressed, do this...
if (isset($_POST['send_comm'])) {
$_POST = array_map('trim', $_POST);
if (!empty($_POST['thought_id']) &&
!empty($_POST['comment_msg'])) {
$comment = htmlentities(strip_tags($_POST['comment_msg']));
$comment = mysqli_real_escape_string($connect, $comment);
$thought_id = mysqli_real_escape_string($connect, $_POST['thought_id']);
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
else {
// empty fields; handle this accordingly
}
}
INSERT INTO user_comments VALUES ('','$comment'
What is that empty string?
I think that is the ID, so, IDs only accepts integer values, you can replace by null, or remove it.
INSERT INTO user_comments VALUES (null,'$comment'
INSERT INTO user_comments VALUES ('$comment'
if you want to use the id out side of the loop you will have to assing it >to a global variable.You will need to declare a variable in the global scope >and then use the global keyword with in the while loop. Once you do this you can use the thought_id variable any were you choose.
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' ORDER BY id DESC");
$thought_id; // Declare the variable outside of the while loop in the global scope
while ($row = mysqli_fetch_array($query)) {
global $thought_id = $row['id'];
/*use the global keyword to assign the the value of this variable to the global variable and you will be able to use it out side of the while loop */
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// for each post a user has made, a new div will be echo's
echo "
<div class='message_wrapper'>
// all content here which displays the message and author.
// consider this anchor link, and see $_GET approach below.
<a href='/inc/del_post.php?id=$thought_id>'>Delete </a>
<div id='toggleComment$thought_id' class='new_comment'>
<form action='' method='post' enctype='multipart/form-data'>
<table>
<tr>
<td>
<textarea id='txtarea' name='comment_msg' cols='80' maxlength='180' placeholder=' add your comment...'></textarea>
</td>
<td>
<input id='send' type='submit' name='send_comm' value='Share'/>
</td>
</tr>
</table>
</form>
</div>
</div>";
} // while loop closed
// sending comments to database
$comment = htmlentities(trim(strip_tags(#$_POST['comment_msg'])));
$comment = mysqli_real_escape_string($connect, $comment);
// if button is pressed, do this...
if(isset($_POST['send_comm'])){
if (!empty ($comment)){
$insert_comment = mysqli_query ($connect, "INSERT INTO user_comments VALUES ('','$comment','$username','$user','0','$thought_id')");
header ("Location: /profile_page/$user");
}
}
?>

Submitting always gets the last value

<form action="" method="post">
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims" ;
$result = mysql_query($sql,$con);
while($row = mysql_fetch_assoc($result)){
?>
<ul class="category_list">
<input type="hidden" value="$id1" name="hidden">
<li><?php echo $row['phonenr'];?><input type="hidden" value="<?php echo $row['id'];?>" name="id"></li>
</ul>
<?php
}
?>
<input type="submit" name="submit">
</form>
So i got the above form where you can select phonenumbers and when you submit them a database should be updated. And there are 23 id's in it. After submitting the form it always takes the last value. What am i doing wrong?
if(#$_POST ['submit'])
{
$id = $_POST["id"];
echo $id;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Change your hidden field name to array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
then on PHP side use loop to retrieve
foreach ($_POST['id'] as $val) {
$id = $val;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Slight modification specified by chandresh_cool, would get the result that you expect.
The input name is replaced with id, so the post key contains only the row[id], not the $_POST['id']
Instead change the name of the hidden field to accept as a array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
Then you can iterate id array as specified by chandresh_cool

How to edit, delete and add in php mysql without jquery or java script?

I am trying to delete , edit and add new recodes on the same page but it seems am failing to make it work .And I do not want to do it using ajax jquery or java script but only php .I need some help please below are my code :
<?php
include_once('con.php');
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
echo "<table border='1' ><tr bgcolor='#eeeeee'><td>Name</td> <td colspan='2'>Action</td></tr>";
while($row = mysql_fetch_assoc($rs))
{
$film_id = $row['film_id'];
$name = $row['name'];
$hometeam= mysql_real_escape_string($name);
echo "<tr bgcolor='#eeeee'><td>$name</td> <td><a href='index.php?film_id=$film_id' name ='edit'>Edit</a></td><td><a href='index.php?film_id=$film_id' name ='delete'>Delete</a></td></tr>";
}
?>
<?php
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
$row = mysql_fetch_assoc($rs);
$film_id= $row['film_id'];
$name = $row['name'];
$name = mysql_real_escape_string($name);
$film_id= $_GET['film_id'];
?>
<?php
if(isset($_POST['edit'])){
?>
<table>
<form action="index.php" method="post">
<tr>
<td>
Name
</td>
<td>
<input type = "text" name = "name" value="<?php echo $name;?>">
</td>
</tr>
<input name="film_id" type="hidden" id="film_id" value="<?php echo $film_id; ?>">
<tr>
<td>
<input type = "submit" name = "submit" value="update">
</td>
</tr>
<?php
$name = (isset($_POST['name']))? trim($_POST['name']): '';
$film_id = $_POST['film_id'];
$sql = "UPDATE filmsbox SET name='$name'
WHERE film_id ='$film_id'";
$result = mysql_query($sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
}
?>
<?php
/*Delete section*/
if(isset($_POST['delete']))
{
$film_id = $_GET['film_id'];
$delete = "DELETE FROM filmsbox WHERE film_id = '$film_id'";
$result = mysql_query($delete);
if($result)
{
echo "Record deleted successfuly ";
}
else
{
echo "No data deleted";
}
}
?>
Couple of pointers:
You only need to escape values before they go into the database, not when they come out and are used in HTML i.e $hometeam = mysql_real_escape_string($name);
You are pulling the same query from the database twice in quick succession which is not needed. You can remove one of the 2 $strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL); sections from the top of your code
You need to run any update/delete queries on the data before you then do your select query to pull out the records for the page, otherwise your changes will not be shown
You should be escaping the values for your update and delete queries to prevent SQL injection
Edit:
To reload the page in an edit mode, you need to change the link URL in the table to something like
<a href='index.php?film_id=$film_id&edit=1' name ='edit'>Edit</a>
Then your edit block needs to be
if ($_GET['edit']) {
I want to be clear this is not in any way a secure method of editing values, as anyone can put ?edit=1 on the url and get to the form

How to handle unknown number of items from a form in php

Working on making an inventory page for work. I have written a page that will loop through my data base and display all of the items in there.
include 'auth.php'; //to change login, please authenticate
$sql="SELECT * FROM `inventory` ORDER BY `id` asc;";
$result=mysql_query($sql);
while($rows = mysql_fetch_array($result)){
echo $rows["name"];
<input type="text" name="<? echo $rows["id"]; ?>" id="<? echo $rows["id"] ?>" placeholder="Who will go in here?" />
}
The above code is doing what I want. I would like to put this in a form and have a submit button. Let's say the form is
<form method="POST" action="page.php">
Now I want to be able to write a page.php so that it can handle all of the data regardless of the number of items. In the past I have done the following
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$phone=$_POST['phonenum'];
$email = $_POST['email'];
$age = $_POST['b18'];
But that won't work as I will have an unknown amount of post. Please write any code you like. I prefer document pages.
$_POST is just an ordinary hash array, so you can loop over it
foreach ($_POST as $key => $value) {
print "{$key}: {$value}<br />";
}
edit
well you need to do some special adjustments, if your values are array values (POST key with [] at the end of the name)
edit
it's of no use if you try
foreach ($_POST as $varname => $value) {
${$varname} = $value;
}
because you don't know the name of the variables;
I will start from your code
include 'auth.php'; //to change login, please authenticate
$sql="SELECT * FROM `inventory` ORDER BY `id` asc;";
$result=mysql_query($sql);
while($rows = mysql_fetch_array($result)){
echo $rows["name"];
<input type="text" name="id[]" id="<? echo $rows["id"] ?>" value = "<? echo $rows["id"] ?>" placeholder="Who will go in here?" />
}
Now in your page.php
<?php
foreach($_POST['id'] as $id):
echo $id;
endforeach;
?>
This will print out all the values of the input named id[]
What i did for you is naming the input with array at the end and then print that array
I hope that's what you want

Categories