show data in multiple textbox in php - php

I want to show all the names of my tb_app which is currently have (4)names stored and show it on my textboxes...can anyone help me make my code work? I'm just a beginner at programming.
current code:
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
$name = $rows['name'];
}
?>
Name List: <br />
<input type="text" value="<?php echo $name[0] ?>" /> <br />
<input type="text" value="<?php echo $name[1] ?>" /> <br />
<input type="text" value="<?php echo $name[2] ?>" /> <br />
<input type="text" value="<?php echo $name[3] ?>" /> <br />
</body>
</html>

Right now you are overwriting the $name variable in each iteration of your loop. You want to treat $name as an array instead, and add an element to the array in each iteration.
Change this:
$name = $rows['name'];
To this:
$name[] = $rows['name'];
You could of course echo your textbox directly inside your while loop as well, and skip the $name variable. However it's good practice to separate your DB or business logic from your display logic, which you are (somewhat) doing. In fact I'd recommend moving your PHP code to the very top of the page, before your opening <html> tag even, and limit how much PHP you mix in with your html.

A more dynamic way (i.e you have less or more then 4 names):
<html>
<head>
<title>test</title>
</head>
<body>
Name List: <br />
<?php
include('include/connect.php');
$sql = "SELECT name FROM tb_app";
while($rows = mysql_fetch_array($sql)){
echo '<input type="text" value="'. $rows['name'] .'" /> <br />';
}
?>
</body>
</html>

You could go even further:
Change name to names:
while($rows = mysql_fetch_array($sql)){
$names[] = $rows['name'];
}
And then
Name List:
<?php foreach ($names as $name): ?>
<input type="text" value="<?php echo $name ?>" /> <br />
<?php endforeach; ?>

Related

PHP- how to get values from checked checkboxes and corresponding textboxes

I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}

$_GET or $_SESSION for passing variable

Hello monsters of programming. I just want to ask a question about using $_SESSION and $_GET. When to use $_GET and $_SESSION? what is the best for passing variable? Im just new to php and html and i don't know what is the best practice. Can someone help me to understand both of them?
Here is the example of my code. I used $_SESSION for passing the variable $newsid;
here is the edit.php
<?php
session_start();
include_once('connection.php');
$sql ="SELECT * FROM news ORDER BY news_id";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
$newsid = $row['news_id'];
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
?>
<div class="fix single_news">
<div class="single_image">
<img src="<?php echo $newsimage; ?>" style="width:200px; height:140px; alt="court">
</div>
<?php echo $title; ?>
<p><?php echo $date; ?></p>
<p><?php echo $content; ?></p>
</div>
<form action="" method="post">
<input type='hidden' name="news_id" value="<?php echo $newsid;?>">
<input type="submit" name="esubmit" value="edit" />
</form>
<hr>
<?php
}
if(isset($_POST['esubmit'])){
$_SESSION['news_id'] = $_POST['news_id'];
header('Location: edit2.php');
}
?>
here is the edit2.php
<?php
session_start();
$id = $_SESSION['news_id'];
include_once('connection.php');
$sql = "SELECT * FROM news WHERE news_id = '$id'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$title = $row['news_title'];
$date = $row['news_date'];
$content = $row['news_content'];
$newsimage = $row['news_image'];
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form method="post" action ="" enctype="multipart/form-data">
Title<input type ="text" name ="title" value="<?php echo $title;?>"/><br>
Date<input type ="text" name="date" value="<?php echo $date;?>" /><br>
Content<textarea name="content"><?php echo $content;?></textarea>
<input type="submit" name="submit" value="Update" />
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $newsimage;?>" alt="your image" style="width:200px; height:140px;"/>
</form>
<hr>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
$_GET is for parameters that are needed during that specific request (or can be easily carried over to other pages), e.g.:
item IDs
current page (pagination)
user's profile name
...
$_SESSION is for data that needs to be persisted across multiple requests, e.g.:
current user's ID
shopping carts
list filters
...
You should use the one that better suits your use case.
That being said, I'd consider storing news_id in the session a bad thing. What if I want to edit multiple items and open multiple browser tabs? I'll end up overwriting my data. Just because you can use sessions doesn't mean you should.

Cant fetch variable after submitting the form

The variable $role_id1 is not being fetched in $role_id in $_POST['add sub menu'].
I want to store $role_id1 in $role_id and insert into database.Afer i click the submit button the role_id1 is fetching the parent menu but after i click add sub menu the role_id is storing 0 at backend.But i want it to store the vale of role_id1 which is being fetched after i click submit.Suggest any solution if possible.
<?php
$dbcon = new MySQLi("localhost","root","","menu");
if(isset($_POST['add_main_menu']))
{
$menu_name = $_POST['menu_name'];
$parent_id = 0;
$role_id = $_POST['role_id'];
$menu_link = $_POST['mn_link'];
$sql=$dbcon->query("INSERT INTO menu VALUES('','$menu_name','$parent_id','$role_id','$menu_link')");
}
if(isset($_POST['add_sub_menu']))
{
$parent_id = $_POST['parent'];
$name = $_POST['sub_menu_name'];
$role_id = $role_id1;
$menu_link = $_POST['sub_menu_link'];
$sql=$dbcon->query("INSERT INTO menu VALUES('','$name','$parent_id','$role_id','$menu_link')");
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Dropdown Menu</title>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>
<body>
<div id="head">
<div class="wrap"><br />
<h1>Back to menu</h1>
</div>
</div>
<center>
<pre>
<form method="post">
<input type="text" placeholder="menu name :" name="menu name" /><br />
<input type="text" placeholder="role id :" name="role_id" /><br />
<input type="text" placeholder="menu link :" name="mn_link" /><br />
<button type="submit" name="add_main_menu">Add main menu</button>
</form>
</pre>
<br />
<pre>
<form method="post">
<select name="role_id">
<option selected="selected">select role id</option>
<?php
$res=$dbcon->query("SELECT distinct role_id FROM menu");
while($row=$res->fetch_array())
{
?>
<option value="<?php echo $row['role_id']; ?>"><?php echo $row['role_id']; ?></option>
<?php
}
?>
</select><br />
<input type="submit" value="submit" name="submit">
<?php if(isset($_POST['submit']))
{
?>
<select name="parent">
<option selected="selected">select parent menu</option>
<?php
$role_id1 = $_POST['role_id'];
$res=$dbcon->query("SELECT * FROM menu where role_id= $role_id1 AND parent_id=0 ");
while($row=$res->fetch_array())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']
;
?></option>
<?php
}
}
?>
</select><br />
<input type="text" placeholder="menu name :" name="sub_menu_name" /><br />
<input type="text" placeholder="menu link :" name="sub_menu_link" /><br />
<button type="submit" name="add_sub_menu">Add sub menu</button>
</form>
</pre>
back to main page
</center>
</body>
</html>
$role_id1 = $_POST['role_id'];
The lifetime of $role_id1 is where your scripts stops (last line) and output is sent to the browser (you see the form again).
So on the line in the top of your code:
$role_id = $role_id1;
$role_id1 doesn't exists anymore. If you view your error-log (or turn on display_errors), you would see a Notice: Undefined variable: role_id1 in ...
If you want to keep that value, put it in a hidden element so that it will be included in the POST-data the next time you submit that form:
echo '<input type="hidden" name="previous_role_id" value="' . htmlspecialchars($_POST['role_id']) . '">';
One sidenote (for completeness), although the element is hidden the value can be altered by the user.

trying to edit SQL via php but keep getting an error

as far as i can see my code is sound however, I keep getting an error
this is the error
Notice: Undefined variable: person in
\sql\modify.php on line 12
here is my code..
<?php
include 'includes/connection.php';
if (!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE ID = $_GET[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
<h1>You are modifying A User</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name<input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description<input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify"/>
</form>
<?php
if(isset($_POST['sumbmit'])) {
$u = "UPDATE people SET `Name` = '$_POST[inputName]', `Description` = '$_POST[inputDesc]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modify";
header("Location: index.php");
}
?>
any Thoughts or am im I just blind???
<?php
include 'includes/connection.php';
// set $person veriable
if (!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE ID = $_GET[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
// if form submit you use update and redirect
else {
$u = "UPDATE people SET `Name` = '$_POST[inputName]', `Description` = '$_POST[inputDesc]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
//echo "User has been modify"; // this not need, bcz execute header('location') redirect you current page
header("Location: index.php");
exit(); //use it after header location
}
?>
<h1>You are modifying A User</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name<input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description<input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify"/>
</form>
You just need to check if you actually got output.
Just a plain example:
if ($person):
?>
<h1>You are modifying A User</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name<input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description<input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify"/>
</form>
<?php
endif;
Remember to always validate your input and output, but also if queries you try to run do produce a result set.
Here's the issue:
<?php
include 'includes/connection.php';
if (!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE ID = $_GET[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
At this point $person is set only if the form hasn't been submitted; but later on:
Name<input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description<input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
You're using it anyway. If the form has been submitted, then you're going to get the warning you're seeing. What you need to do is something like:
if (isset($_POST['submit'])){
$name = $_POST['name'];
$description = $_POST['description']
} else {
$q = "SELECT * FROM people WHERE ID = $_GET[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
$name = $person['name'];
$description= $person['description'];
}
And then:
Name<input type="text" name="inputName" value="<?php echo $name ?>" /><br />
Description<input type="text" name="inputDesc" value="<?php echo $description; ?>" />
The variables are now set either way.
A couple of other things - you're not doing any error checking to see if your query has worked; if the query fails, your code will carry on regardless.
Secondly, the mysql_ functions are deprecated and will stop working at some point; you should look at moving to using mysqli_* or PDO instead.

In PHP how to output the contents of a radiobox array using POST?

I want to output the values of the checkbox in the same way I'm outputting the values from the text fields. Since the checkbox can have multiple inputs I'm using an array for that but trying to cycle through the array for values hasn't worked for me.
tried foreach($type as $item) and echoing $item within the HTML like it says in the PHP book I have but that hasn't worked.
How should I do and where should the code be? I'm also unable to use PHP within the HTML for some reason, I'm not sure why that is or if its something to do with the echo<<<_END or not. Help appreciated.
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre'];
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = $_POST['type'];
else $type = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: $game in the $genre genre and of the type<br />
<form method="post" action="formtest.php">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
_END;
?>
With the form as it is now, $_POST['type'] will be an array since it's using checkboxes (and named appropriately), not radios. Here I just implode it for display, but you can loop through it like any array. It should be worth noting that any time you're wondering what a form is giving you, you can var_dump($_POST) or var_dump($_GET) depending on where the data is coming from. It helps a lot with debugging.
Here's what I got, I switched from heredoc, but your heredoc should work fine if you add $type back in somewhere, I didn't notice it in the original code:
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre']; //Edit: Fixed line, oops
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = implode(', ',$_POST['type']);
else $type = "(Not entered)";
//Normally I'd specify a charset, but for simplicity's sake I won't here.
$type = htmlspecialchars($type);
$game = htmlspecialchars($game);
$genre = htmlspecialchars($genre);
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in
the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
Addendum:
If you switched and used radios like
<input type="radio" name="type" value="Downloadable" />
$_POST['type'] would be a simple string since you can only select one of the set.
To the file you post it the type[] will be saved as an array. For example
$a=$_POST['type'];
Although I don't find any point in doing this to radio-buttons, because their purpose is to pass only 1 value(unless you want specifically to).
Ok, first you don't need to echo the entire html output. Second your questions says radio buttons, but the html shows checkboxes. A radio field will only produce one result so you don't need [] after then name. Checkboxes will return an array when named with a []. So if you are using checkboxes you will need to process the result as an array. If you change the field to radio it should work fine.
<?php // formtest.php
if (isset($_POST['game'])) {
$game = $_POST['game'];
}
else { $game = "(Not entered)"; }
if (isset($_POST['genre'])) {
$genre = $_POST['genre'];
}
else { $genre = "(Not entered)"; }
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else { $type = "(Not entered)"; }
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="test.php">
What is your game?
<input type="text" name="game" <?php if ($game != "(Not entered)") { echo "value='" . $game . "'"; } ?> />
<br />
What is your genre?
<input type="text" name="genre" <?php if ($genre != "(Not entered)") { echo "value='" . $genre . "'"; } ?> />
<br />
Type?
Retail <input type="radio" name="type" value="Retail" <?php if ($type == "Retail") { echo "checked"; } ?> />
Downloadable <input type="radio" name="type" value="Downloadable" <?php if ($type == "Downloadable") { echo "checked"; } ?> />
Free <input type="radio" name="type" value="Free" <?php if ($type == "Free") { echo "checked"; } ?> />
<br />
<input type="submit" />
</form>
</body>
</html>

Categories