How to put a php variable into an HTML form - javascript

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.

Related

Use array to post html form with every aray value ony by one

I am wondering if the folowing is possible.
I fetch a list of names as an array from a SQL database. I need all those names to be posted with a html form one by one. This action should be activated with one button. When the button is clicked the names should be posted one by one untill all names are posted, then stop. So probebly jquery or javascript is needed but that is new for me. I have been searching but I can not find anything that can help me accomplisch this.
I am sorry for asking this question and my language (english is not my main language) but I don't know if this is even possible and I cant find any corresponding topics while researching..
PS: I can not use Ajax for the post !!
Example to get the names:
$stmt = $mysqli->prepare("SELECT username FROM example WHERE examplefield = 1");
$stmt->execute();
$result = $stmt->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result->fetch_assoc())
{
$arrayusername[] = $rowid['username'];
}
I need all the names from the $arrayusername[] to be posted with below form one by one by pressing the following button
<input type="button" value="Post all names one by one"
onClick="sendallvalues('???') "class="example_c" />
// The button should do the following post name 1, end. post name 2 end, post name 3 end. stop script when all names are posted.
<form method="post" target="_example" action="https://www.example.nl">
<input type="hidden" value="<?= $arrayusername[] ?>" name="postvalue" >
</form>
// should be hidden to the user and is only ment for the name atrribute to have a place ! All the stuff needs to happen by pressing that one button !
<script>
function sendallvalues(???) {
//I have no Idea where to begin to make this happen.. But it should post the form one by one with one value at the time untill all names are posted.
}
</script>
Maybe you can explain more detailed what you need.
The value attribute should have one name and you create different input fields.
<form method="post" target="_example" action="https://www.example.nl">
<input type="hidden" value="<?= $arrayusername[] ?>" name="postvalue" >
<input class="example_s" type="submit" value="Post name">
</form>
should be
<?php
$arrayusername = array('Name1','Name2');
echo '<form method="post" target="_example" action="https://www.example.nl">';
foreach ($arrayusername as $key => $value) {
echo '<input type="hidden" value="' . $value .'" name="name-' . $key . '" >';
}
echo'<input class="example_s" type="submit" value="Post name">';
echo '</form>'
?>

Take ID From Form Option & Use It To Populate Multiple Fields

I have looked throughout the site and nothing has quite matched what I'm after. I have a form which starts of asking the client to choose the company name from a dropdown. The dropdown is populated from a query as such:
<select name='company_name' id='dropdown'><?php
$result = mysqli_query($con,"SELECT ID, TITLE FROM b_crm_company");
while($row = mysqli_fetch_array($result))
{
$companyName = $row['TITLE'];
$companyID = $row['ID'];
print "<option value='$companyID'>$companyName</option>";
}
?></select>
I then have 3 forms text fields that I need pre-populating based on what is selected from the above and I'm not sure how to do it. So my next three form fields:
<input type="text" value="$contactName" name="contactName">
<input type="text" value="$contactTelephone" name="contactTelephone">
<input type="text" value="$contactEmail" name="contactEmail">
The select statement I'd need to get these three values:
SELECT COMPANY_ID, NAME, TELEPHONE, EMAIL FROM b_crm_contact
WHERE COMPANY_ID = $companyID
The $companyID obviously being pulled from the dropdown at the start. How can I pull the information to the next fields? I'm assuming javascript but not sure how to write it.
Thanks in advance
you need to call ajax on click of your drop down select item
and then need to return string or json from that php file and then parse and put values in appropriate fields
something like this:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});

Redirect user back to registration page but keep their filled in form in php

I have a registration.php page and another registration_checker_page.php.
If username and / or email is taken after they submit, then it'll redirect them back to the previous (registration) page.
But then their filled in data is lost. Is there a way to redirect them without clearing their data?
if(mysql_num_rows($queryUser) > 0){
echo '<p><div id="redirect"/></p>';
}
function redir {
code ... location.href = "registration.php";
}
Edit: By filled data it is first name, username, postcode etc. But other information like password etc will be removed.
You can use session or cookie for same
if(mysql_num_rows($queryUser) > 0){
echo '<p><div id="redirect"/></p>';
}
function redir() {
$userName = $_POST['username'];
$email = $_POST['email'];
setcookie("userName", $userName, time()+3600); /* expire in 1 hour */
setcookie("emial", $email, time()+3600);
code ... location.href = "registration.php";
}
And at your form
<input type="text" name="userName" value="<?php echo isset($_COOKIE['userName']) ? $_COOKIE['userName']:'' ?>">
<input type="text" name="email" value="<?php echo isset($_COOKIE['email']) ? $_COOKIE['email']:'' ?>">
You can above same with using session.
Hope this will help
The best way to solve this, in MNSHO[1], is to make sure those values are never lost in the first place.
Lets assume, for the same of discussion, that you have a field in your HTML called 'username'
If you are using a GET (or a regular redirect), you can include username as part of the
querystring, so it is available on the registration page.
window.location.href = "registration.php?username=" . $_REQUEST(username);
And then, on your registration page:
<input name="username" type="text">
What you'd want to do is look and see if you have an existing value that came in.
<?php
$usernameValue = "";
if (isset($_REQUEST['username'])) {
$usernameValue = $_REQUEST['username'];
}
// Typing on the fly, I may have the type of quotation marks
// flipped around. N
echo '<input name="username" type="text" value="$usernameValue">';
// or this...
echo "<input name='username' type='text' value='$usernameValue'>";
?>
Now, if you are redirecting to this page from another...
[1] My Not-So-Humble Opinion
You could save them a get variable and append that to the file you are referring them too, or do it server side and save them by a temporary ID.
First possibility:
location.href="registraion.php?e=thisdudes#ema.il&u=thisdude"
Use AJAX to check for duplicate username/email immediately after the textbox loses focus and notify the user accordingly. That is how modern pages do it.
Is there a reason why you are waiting for the user to fill the complete form before checking for duplicate username/email?

Hidden values in php echo

I have this query in php code:
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
I have echoed the vName.
echo $row['vName']."\n";
The above values appear in a autocomplete textbox.
In the same aboce echo statement I want to pass 'id' as hiden value. is it possible? I wan to retrieve it in another page.How do I do this?
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
$hid='<input type="hidden" name="xyz" id="abc" value="'.$row['id'].'" />';
echo($hid);
echo $row['vName']."\n";
I hope you get the idea.
Echo it out to a hidden input field,
<input type="hidden" name="hidden_id" id="my_hidden_id" value="<?php echo $row['id'];?>"/>
This way you can pass it with a form if you are submitting one or simply add an id to it and get the value to pass to the next page.
I would first make a variable of $row['id'] and when you're still in your form but outside the textbox do this:
<?php echo "<input type='hidden' name='id' value='".$yourvariable."'/>";?>
If it must be completely hidden i recommend using php-sessions.
I guess you want to do that if you want to retrieve the id in other page , you better do this :
<?php echo $row['vname'] ?>

ajax display text on submit

I have a simple form with a submit button (below). I am trying to let the user type in the text box then when he/she clicks submit the page will refresh and echo out what they typed in a div. The data the user types is stored in a database before being echoed. The problem is that when I click submit, the input doesnt show immediatly. I have to click refresh for it to show and when I do my browser gives me a popup (safari) asking to resend the data. This will result in duplicate data inserted in the DB. I have a feeling I need to use javascript and I could also make it more elegant with a fadeIn, but I dont know how to do that. I guess I'm asking if there's a way to use javascript to take a user's text and insert it into a mysql DB and also display it after submit is clicked all on 1 or 0 (prefereably) refreshes. thanks
Here's my code:
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
<?php
$input=$_POST['text'];
$put=mysql_query("INSERT INTO table VALUES ('$input')");
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo "</div>";
?>
I would put the php statements before you're actual html code and would modify you're code like this
<?php
if (isset($_POST['text']))
{
$input = mysql_real_escape_string($_POST['text']);
$put=mysql_query("INSERT INTO table VALUES ('$input')"); //At this point the info has been put inside the DB
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo mysql_query("SELECT * FROM table");
echo "</div>";
}
?>
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
The reason why you don't see it is that the HTML is loaded before you php I think. So I would do a php page where all the sql treatement would be done and once that is done recal you index.php and in there query you're information from the database.
Setting aside SQL injection attacks your code is vulnerable with, the standard practice is to respond to the POST with a redirect back to where the form was. In your case, it will be the page which runs SELECT from table.
No need to use AJAX here. Just make sure that you do one of the following:
Make sure you SELECT from the DB after you have INSERTed the data.
Better, is that if ($_SERVER['REQUEST_METHOD'] == 'POST'), then rather than performing an extra SQL query, just display the POSTed value since you already know it.
A side note on your code sample. If you don't have magic_quotes enabled, it's susceptible to SQL injection, so make sure you properly escape user input before using it in queries.

Categories