Dynamic form input names allocated to $_POST - php

I have a form that has the name value of the input element dynamically populated from a mysql query. Problem I am having is that I dont know to assign the value to a valid variable on form submission for later use, i cant declare the variable earlier in the scrip because i dont know it until the query is executed? how do i assign the name value to a $_POST variable? thanks.
my code
$con = new mysqli('localhost', 'jolly' ,'xxxx', 'jolly');
$query = 'SELECT * FROM names ORDER BY name ASC';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<p align="right"><?php echo $row['name'] ?>:
<input type="int" name="<?php echo $row['name'].'_score' ?>" />
</br>
<?php } ?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>

Just use the value attribute of tag like this
<input type="text" name="somename" value="<?php echo $row['name'].'_score' ?>">
i am sure this will help

One possibility to solve your conundrum would be to run the sql query before generating the html and storing the query results in an array / object / session. Once the values are stored you can generate the html but by that stage would know the names and values from the db call.
$con = new mysqli( 'localhost', 'jolly' ,'xxxx', 'jolly' );
$query = 'select * from `names` order by `name` asc';
$result = mysqli_query( $con, $query );
$data = array();
/* add content from db to storage object */
while( $row = mysqli_fetch_assoc( $result ) ) $data[]=$row['name'];
/* possibly save as a session? */
$_SESSION['names']=$data;
/* generate the html */
<form method='post' name='names' action='/path/to/script.php' enctype='application/x-www-form-urlencoded'>
<?php
foreach( $data as $i => $name ){
echo "<p align='right'>{$name}<input type='int' name='{$name}_score' /></p>";
}
?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>
if you stored the data in a session you should be able to access it in the form handler script if required.

You do not need to assign an explicit name to an input. What you have to is distinguish the forms. When submitting the post, the entire form is submitted.
your.php:
<?php
$var = $_post['data'];
...
>
form.php:
...
$con = new mysqli('localhost', 'jolly' ,'xxxx', 'jolly');
$query = 'SELECT * FROM names ORDER BY name ASC';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<form id = "form_<?php echo $row['name'].'_score' ?>" name = "form_<?php echo $row['name'].'_score' ?>" action = "your.php" method = "POST">
<p align="right"><?php echo $row['name'] ?>:
<input type="int" name="data" value= "<?php echo $row['name'].'_score' ?>" />
</br>
<?php } ?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>

Related

Checkbox in a while loop php

I have a check box inside a while loop like this:
<form method="POST">
<?php $sql= mysql_query("SELECT * FROM names WHERE `id` ='$id' ");
while ($get = mysql_fetch_array($sql)){ ?>
<input type="checkbox" name="id_names" value="<? echo $get ['id'];?>"><?php echo $get ['name']; ?>
<?php } ?>
<input id="submitbtn" type="submit" value="Submit" /><br><br>
</form>
The problem is at this part I am unable to get specific checkbox properties and even if the user selects two check boxes I am unable to echo the id out
<?php
if(isset($_POST['id_names']))
{
$id_names= $_POST['id_names'];
$email = mysql_query("SELECT `email` FROM users WHERE `id` = '$id_names' ");
while ($getemail = mysql_fetch_array($email))
{
echo $getemail['email'];
}
}
?>
I have tried searching for answers but I am unable to understand them. Is there a simple way to do this?
The form name name="id_names" needs to be an array to allow the parameter to carry more than one value: name="id_names[]".
$_POST['id_names'] will now be an array of all the posted values.
Here your input field is multiple so you have to use name attribute as a array:
FYI: You are using mysql that is deprecated you should use mysqli/pdo.
<form method="POST" action="test.php">
<?php $sql= mysql_query("SELECT * FROM names WHERE `id` =$id ");
while ($get = mysql_fetch_array($sql)){ ?>
<input type="checkbox" name="id_names[]" value="<?php echo $get['id'];?>"><?php echo $get['name']; ?>
<input type="checkbox" name="id_names[]" value="<?php echo $get['id'];?>"><?php echo $get['name']; ?>
<?php } ?>
<input id="submitbtn" type="submit" value="Submit" /><br><br>
</form>
Form action: test.php (If your query is okay.)
<?php
if(isset($_POST['id_names'])){
foreach ($_POST['id_names'] as $id) {
$email = mysql_query("SELECT `email` FROM users WHERE `id` = $id");
$getemail = mysql_fetch_array($email); //Here always data will single so no need while loop
print_r($getemail);
}
}
?>

Weird error when updating database using php

I have a weird problem in which if I delete the line Type doctor name <input type="text" name="new_Doctor_name" value="<?php echo $row1[3]; ?>" ><br />, I cannot update my records and get the notice Undefined variable: row1. However, if I keep this line, which I copy from another table, I can update just fine.
Please explain this. Any help will be highly appreciated.
<?php
include_once('Connect.php');
if( isset($_GET['edit1']) )
{
$id = $_GET['edit1'];
$res1= mysql_query("SELECT * FROM department WHERE Dept_name='$id'");
$row1= mysql_fetch_array($res1);
}
if( isset($_POST['new_Doctor_name']) )
{
$id = $_POST['id'];
$new_Dept_name = $_POST['new_Dept_name'];
$new_Ward = $_POST['new_Ward'];
$sql1 = "UPDATE department SET Dept_name='$new_Dept_name', Ward='$new_Ward' WHERE Dept_id='$id'";
$res2 = mysql_query($sql1) or die("Could not Update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=Department_viewtable.php'>";
}
var_dump($row1);
?>
<FORM ACTION="Department_dmod.php" METHOD="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
***Type doctor name <input type="text" name="new_Doctor_name" value="<?php echo $row1[3]; ?>" ><br />***
Type Department Name <input type="text" name="new_Dept_name" value="<?php echo $row1[1]; ?>" ><br />
Type Department Ward <input type="text" name="new_Ward" value="<?php echo $row1[2]; ?>" >
<INPUT TYPE="SUBMIT" NAME="UPDATE" VALUE="UPDATE">
<p><a href=Department_viewtable.php>Back to the Department table</a></p>
<p><a href=Main_Menu.php>Back to Main menu</a></p>
</FORM>
The if() statement :
if( isset($_POST['new_Doctor_name']) )
Will only ever be executed if an input element exists in the POST data with a name of new_Doctor_name. If you remove it from the DOM, it will not be passed with the request, and thus the queries won't execute.
It may be better to check for the presence of the UPDATE variable inside the POST request:
if(isset($_POST['UPDATE']))
{
$id = $_POST['id'];
$new_Dept_name = $_POST['new_Dept_name'];
$new_Ward = $_POST['new_Ward'];
$sql1 = "UPDATE department SET Dept_name='$new_Dept_name', Ward='$new_Ward' WHERE Dept_id='$id'";
$res2 = mysql_query($sql1) or die("Could not Update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=Department_viewtable.php'>";
}
It's also worth noting that the mysql_* family of functions is now deprecated. Instead, you should look at MySQLi or PDO. Finally, your code is open to SQL injection, so I'd recommend looking at Prepared Statements, too.
The variable row1 is set in this part of the code. If the variable is returning an error that it has not been defined this means that the code below has not been executed. This code is only ran if the $_GET['edit1'] variable is set.
if( isset($_GET['edit1']) )
{
$id = $_GET['edit1'];
$res1= mysql_query("SELECT * FROM department WHERE Dept_name='$id'");
$row1= mysql_fetch_array($res1);
}

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

How to read/send post data with php and hold a variable in it

I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.

Edit record (should be so easy)

I have looked everywhere here in Stackoverflow and I´ve searced 16.493 sites on Google but no answers to the most basic thing in php (edit record)
I´ve managed to code the most complicated stuff - but this is like a cancer and would also help others.
I have to files - edit.php - and update.php
edit.php works and it retrieves the data from the record
Here is the edit.php
<?php
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM cloudbig WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
?>
<form name="form1" method="post" action="update.php">
<input type="text" name="fs" value="<?php echo $texti ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
<?php
}
?>
and here is update.php
<?php
$id = $_REQUEST["id"];
$fs = $_POST["fs"];
$texti = $_POST["texti"];
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("db") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE cloudbig SET fs = '$fs', texti = '$texti' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
I´ve done a whole news/online magazine site in php but simple edit.php function is a problem
I think that the short answer is that you never post the "id" up to the update.php script. Your form needs to look like this:
<form name="form1" method="post" action="update.php">
<input type="hidden" name="id" value="<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will send the id into the POST array where it can be accessed by $id = $_REQUEST["id"];
You can also accomplish this by sending it via _GET by modifying the form action:
<form name="form1" method="post" action="update.php?id=<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will put it in the $_GET array where it will also be seen in the $_REQUEST array.
Lastly, there are some MAJOR ISSUES with your code:
First and foremost, it is subject to SQL injection! You MUST escape
your variables before passing them into a MySQL query.
Second. As pointed out by iDifferent, you appear to bve echoing the wrong value into the fs field (you're setting it equal to the texti field)
Third, why do you have this loop?
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
If you're fetching by ID you should never have duplicates. Make sure that ID is a primary key and there is no reason to check for multiple rows.

Categories