Sorry, newbie question I know, however I've currently got mySQL results only showing when using the echo command through PHP etc..
Now, I am able to source the information fine, however I would like the result of a query to show up in a form e.g.
Rather than :-
$loggedinuser = $session->username;
//$query = "SELECT surname, firstname FROM PASSENGER WHERE username = '$jared'";
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
echo $row['surname'] ." ". $row['destination'];
}
echo mysql_error();
I would like to print the SQL result in a HTML form...e.g. one that follows the convention of:-
Surname: <input type="text" name="firstname" value="echo $row['surname']/>
If you see where I am coming from. Is this really bad practice using forms to display mySQL results, or can it be done? If not really, what ways would you recommend I print the data? In a table of some sort, but how can I then use fields?
Regards,
Tom.
Something like this work:-
<?php
$loggedinuser = $session->username;
//$query = "SELECT surname, firstname FROM PASSENGER WHERE username = '$jared'";
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
"<form>"
<input type="text" name="firstname" value="<?php echo {$row['surname']} ?>" disabled />
"</form>"
}
echo mysql_error();
?>
How can a new line be added between echo's in the following code please?
echo ' Surname: <input type="text" name="surname" value="'.$row['surname']. "\" disabled /> ";
echo 'Forename: <input type="text" name="surname" value="'.$row['forename']. "\" disabled />";
echo 'Email Address: <input type="text" name="surname" value="'.$row['emailAddress']. "\" disabled />";
echo 'Preference ID: <input type="text" name="surname" value="'.$row['dob']. "\" disabled />";
echo 'Seat Number: <input type="text" name="surname" value="'.$row['seatNo']. "\" disabled />";
echo 'Group ID: <input type="text" name="surname" value="'.$row['groupID']. "\" disabled />";
<input value="<?php echo $row["firstname"]; ?>">
<input type="text" name="firstname" value="<?php print($row['surname']); ?>"/>
or
<input type="text" name="firstname" value="<?=$row['surname']?>"/>
Using anything to display the information is good, until you are not allowing the users to be able to change those values. You can also display using tables/divs or anything else you can think of. Forms are a very good method too(imo). Also, you can use a disabled property, to not to allow anyone to change those values you put in your Form's input boxes.
<input type="text" name="firstname" value="<?php echo {$row['surname']} ?>" disabled />
EDIT Putting up the while loop here:
while($row = mysql_fetch_array($result)) {
echo "Surname: <input type=\"text\" name=\"firstname\" value=\"" . {$row['surname']} . "\" disabled />"
}
If you are merely needing to display data in a read-only fashion, you don't really want to "show the query", you want to print the results of said query in a readable fashion. I'm sure there are certain instances where you would need to print SQL to the users, but those situations are probably rather slim. As others have said, it is also extremely poor practice to allow the user to submit any type of SQL and use it - the mantra is that any user input should always be considered malicious user input - you must validate and sanitize everything before you send it to your database.
This being said, it looks like you just want to show a form with results from your query, which you were incredibly close on. The only issue you may have is if your query returns 2 or more rows, in order to get PHP to automatically bind the submitted values to an array, you'll have to sequentially name them so they show up as: firstname[0] , firstname[1] and so on. Just start an int that you can increment through each time:
$loggedinuser = $session->username;
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
$i = 0;
while($row = mysql_fetch_array($result)) {
$surname = $row['surname'];
$destination = $row['destination'];
echo '<input type="text" name="firstname[$i]" value="$surname" />';
echo '<input type="text" name="destination[$i]" value="$destination" />';
$i++;
}
Let's say you had two rows show up in your query, here's what would result (with added formatting):
<input type="text" name="firstname[0]" value="Bill" />
<input type="text" name="destination[0]" value="Rococo" />
<input type="text" name="firstname[1]" value="Mandy" />
<input type="text" name="destination[1]" value="Philadelphia" />
EDIT: To add newlines to the HTML being outputted, just add a <br /> tag for each newline:
echo '<input type="text" name="firstname[$i]" value="$surname" /><br />';
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
echo '<form>';
echo ' Surname: <input type="text" name="surname" value="'.$row['surname'].'/><br/>';
echo ' Below is my Destination<br/>';
echo ' Destination: <input type="text" name="surname" value="'.$row['destination '].'/>';
echo '</form>';
}
Try this
Related
So im still relatively new to php and im trying to create a form that autofill's with information from a table. The table is called students and has the students id, first and last name, and their address. Im trying to make it so it only autofill's with the information of the student with a certain id, for example if the students id is 102 it fills the textboxes with their info.
I have some code which i thought would work but its telling me somethings wrong with the while loop and i don't know what.
Edit: The error i keep getting is this:"mysqli_fetch_assoc() expects parameter 1 to be mysqli_result".
PHP code:
<?php
require_once ('Connection.php');
$query = "SELECT * from students where Id = 102";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
?>
Html Form:
<form action="http://localhost/test.php" method="post">
<p>Student ID:
<input name="stu_id" size="5" value="<?php echo $row['student_id']; ?>" pattern="^\d{3}" required autofocus /><?php echo $row['student_id']; ?>
</p>
<p>First Name:
<input type="text" name="fname" size="30" value="<?php echo $row['stu_Fname']; ?>"/>
</p>
<p>Last Name:
<input type="text" name="lname" size="30" value="<?php echo $row['stu_Lname']; ?>"/>
</p>
<p>Address:
<input type="text" name="address" size="30" value="<?php echo $row['stu_addr']; ?>"/>
</p>
<p>
<input type="submit" name="submit" value="Send"/>
</p>
</form>
EDIT: Connection code:
<?php
DEFINE ('DB_User', 'testuser');
DEFINE ('DB_Password', 'abc123*');
DEFINE ('DB_Host', 'localhost');
DEFINE ('DB_Name', 'student');
//start database connection
$dbc = new mysqli(DB_Host, DB_User,DB_Password,DB_Name);
if(mysqli_connect_errno())
{
printf("can't connect to database.", mysqli_connect_error());
exit();
}
?>
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
You're not actually accomplishing anything within the while loop above. There is no assignment, nor output.
Each iteration of the while loop will grab a row (if there is one in the database). Assuming that the row has the four columns you've listed, you can print the data to the screen. For example:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['student_id'] . ", ";
echo $row['stu_Fname'] . ", ";
echo $row['stu_Lname'] . ", ";
echo $row['stu_addr'];
}
Assuming you're outputting a form for each student, you can place the form logic within the while loop.
I am a complete beginner, so please bear with me. This is just a test project I am putting together to try to teach myself some of the basics.
I know that a lot of my commands are outdated and/or susceptible to injection, but I'd rather stick with this for now (many reasons).
I just had a question about trying to use SELECT from WHILE, and figured that out and got it to echo the correct response on the page.
Now, how do I make it echo that as a value for an HTML text box? It won't work, and I've tried to look for typos but I don't know what I am doing, frankly.
I see that the $studentid and $teacherinfo show fine, I presume because they are normal variables.
Can I somehow define two more variables for first name and last name further up in the page so that I do not need to include so much code in each input (and to keep it from being buggy)?
Here is my code for the page. The inputs will be hidden, but I have been making them text boxes for debugging purposes.
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
?>
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<h5>Student id: <?php echo $studentid ?></br>
Student first name: <?php
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
?>
</br>
Voted for: <?php echo $teacherinfo ?>
</h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['first_name'];
} ?>"/>
</br>
<input type="text" name="last_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['last_name'];
} ?>"/>
</br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
You can't use while because your query return only one student. You have to use if instead of while. If your query return many students you can use while.
Try this code:
<?php
if($row = mysql_fetch_array($result)){
?>
Student first name: <?php echo $row['first_name'];?>
</br>
Voted for: <?php echo $teacherinfo ?></h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php echo $row['first_name'];?>"/></br>
<input type="text" name="last_name" value="<?php echo $row['last_name'];?>"/></br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
<?php
}
?>
I hope this help.
I tried to build a code that will help you. Remember that you use last_name, but does not return the field in SQL.
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name`,`last_name`,`student_id` FROM `students` WHERE student_id = $studentid",$connection);
while($row = mysql_fetch_array($result)){
echo "<h5>Student id: $row['student_id'] </br>" .
"Student first name: $row['first_name'] </br>" .
"Voted for: $teacherinfo </h5> " .
"<input type='text' name='student_id' value='$row[\'student_id\']' /></br>" .
"<input type='text' name='first_name' value='$row[\'first_name\']' /></br>" .
"<input type='text' name='last_name' value='$row[\'last_name\']' /></br>" .
"<input type='text' name='teacher' value='$teacherinfo' /></br>"
}
?>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
WHILE I left because I do not know if your query can return more than one record, despite appearing to be a key. If you do not need to check the response of the Ragnar.
I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }
I'm trying to build a page where my users can paste in multiple item #s for that product and it will give them the parent model # for that particular item, where items are given individual identifiers.
However, my users paste there information into the textboxs, but it doesn't pull anything up. When I had one value to search it was able to find the items. My table structure is very simple.Fcsku varchar(45), fnsku varchar(45), updated time(45 are not important to this function).
Here is my query Updated:
<form action="" method="get">
Paste your ZZZ's here: <br><input type="text" name="item" id="textbox"/><br>
<input type="text" name="item2" id="textbox2"/>
<script>document.getElementById('textbox').focus()</script><br />
<input type="submit" value="Submit"/>
</form>
<?php
if (!empty($_REQUEST['item'])) {
$item = mysql_real_escape_string($_REQUEST['item']);
$item2 = mysql_real_escape_string($_REQUEST['item2']);
$sql = "select * from oak3_zzz_to_boo WHERE fcsku like '%".$item."%' or fcsku like '%".$item2."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)) {
echo "<font color=red size=7>";
echo '<center><br /> Parent ASIN: '.$row['fnsku'];
echo "</center></font>";
echo "<br><br><br><br><br>";
}
}
?>
This worked at my server:
<form action="" method="post">
Paste your ZZZ's here:<br />
<input type="text" name="item" id="textbox" /><br />
<input type="text" name="item2" id="textbox2"/><br />
<input type="submit" value="Submit" name="submit"/>
<script>document.getElementById('textbox').focus()</script>
</form>
<?php
if (isset($_POST['submit'])) {
$item = mysql_real_escape_string('%'.$_POST['item'].'%');
$item2 = mysql_real_escape_string('%'.$_POST['item2'].'%');
$sql = "SELECT * FROM oak3_zzz_to_boo WHERE fcsku LIKE '" . $item . "' OR fcsku LIKE '" . $item2 . "'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_assoc($r_query)) {
echo "<font color=red size=7>";
echo '<center><br />Parent ASIN: ' . $row['fnsku'];
echo "</center></font>";
echo "<br /><br /><br /><br /><br />";
}
}
?>
I want to show the selected ID data in the form and EDIT it and UPDATE in the database. I selected the data from the database and put it in the input tag but it doesn't work. Please help!
<html>
<body>
<?
$db = mysql_connect("localhost", "root","");
mysql_select_db("db_ncs",$db);
$id = $_GET['s_id'];
if($id)
{
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result);
}
?>
<form method="post" action="update.php">
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
<?
if(isset($_POST['update']))
{
$name = $_POST['s_name'];
$contact = $_POST['s_contact'];
$address = $_POST['s_address'];
$email = $_POST['s_email'];
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
$res = mysql_query($sql);
if($res)
{
echo "Upadate Successfull!";
}
else
{
echo "Sorry!";
}
}
?>
</body>
</html>
You forgot to pass the id.
Add this between the <form> tags.
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
You also need to make your methods consistent. The form submits the data via method="get" but you ask for it via $_POST. You also need to make the input names consistent with the names you ask for, by either adding or removing the "s_" in the appropriate places.
Not really an answer to your question, but i have to point you to some omissions in your code:
if $_POST['update'] is set, that doesn't mean the other variables are also set. They can be empty if user didn't enter anything in a field. You should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
In the form you have method="get" but you use $_POST in your PHP code. Try to define your form as below:
<form method="post" action="update.php">
Your SQL query should be (added quotes):
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
Try adding this after mysql_query:
$result = mysql_query($sql) or die(mysql_error());
Do not use mysql_* functions, they are no longer maintained: use PDO of MySQLi.
Doesn't he have to use the $row = mysql_fetch_assoc($result) to get the results?
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
http://php.net/manual/en/function.mysql-query.php
above is just an example.
update:
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result); // I think you have to add this line here, don't you?
?>
<form method="post" action="update.php">
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
update 2:
when you are going to update, the method up there $id = $_GET['s_id']; is still looking for a param called 's_id' will come via HTTP GET, but it doesn't!
a quick workaround may be this,
<form method="post" action="update.php?<?php echo $id;?>">
and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
update 3:
Hmm, You still need this <input type="hidden" name="s_id" value="<?php echo $id;?>" /> and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
Your form has fields like name="contact", but when you try to get the values you use $_POST['s_contact']. These need to match.
The reason you need the hidden s_id field in the form is so that you will update the same row that was edited. Your UPDATE statement contains WHERE s_id=$id, so you need to get the original id this way. It's hidden because you don't want the user to be able to change the ID when editing.