简体   繁体   中英

How to put a php variable into an HTML form

I have code that queries an SQL database and displays all of the users in a table, that all works fine, from there you are able to click any user and it displays another table that contains all of their information, that also works fine.

The problem I am running into here is on the page that displays the table of the selected users information. On that page I have a button that allows the user information to be edited and update the DB.

Here is the code for the button:

 print "<form method='post' action='adminedituser.php'>
<input type='hidden' name='id' value='$id' />   
<input type='submit' value='Click here to edit this user' />
</form>";

When I click this it takes me to a page with an input box that needs to display the current username and allow the user to put in a new value and submit.

I'm trying to call a php variable inside of the HTML form I have:

<?php

$id = filter_input(INPUT_POST, "id"); 
//Make db connection
$conn=mysql_connect("localhost","root","")or die(mysql_error());

//Step 2: select your db to use
mysql_select_db("final",$conn);

//Step 3: Write the sql that we want to run against the database
$result = mysql_query("select id, firstname, lastname, email, phone, username, password, favchar, bio from user where id=$id");

$username = $result["username"];

?>


<form method='post' id='myForm' name='input' action='adduser.php'>
Username: <input type='text' value="<?php echo ($username); ?>" id='uName' name='uName'>
<input type='submit'>
</form>

The problem is that the variable $username is not being displayed as the text box value.

What am I doing wrong?

Firstly, if I don't say it someone else is: Use mysqli instead of mysql . You can still use the procedural style, if you want (although I can say firsthand it is VERY easy to learn the object style), you just need to do a quick brush up on mysqli . Mysql is deprecated, so it is sort of useless to use. You'll have to learn it eventually, so when you're building a new program, it might be easiest.

Moving on to what you are doing wrong, is that you have not actually fetched anything. MySQL will give you an object, and then you need to sort the rows.

So, what you need to do is pull mysql_fetch_array .

You can do so like this:

while($row = mysql_fetch_array($result)) {
    $username = $row["username"];
}

The form code shuld be changed to:

<input type='hidden' name='id' value='<?= $id ?>' />

You forgot to "print" the $id value.

and the code of adminedituser.php:

$id = filter_input(INPUT_POST, "id"); 

Get the "id" field from POST request of your form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM