Autopopulate an input field from database - php

I am trying to auto-populate an input field with contents from the database, I have successfully fetched the data from the database but am confused to how to populate the input fields dynamically, in that when a user visits the page the input field is added, they find the input field already filled, but they can edit.
Below is the code am using to fetch the data from the database:
function fetch_user_data() {
global $wpdb;
$user_ID= get_current_user_id();
$result = $wpdb->get_results ( "SELECT * FROM mydbtable WHERE user_id = $user_ID ");
foreach ( $result as $print ) {
$data= $print->address;
echo json_encode($data);
}
}
The html input field looks like this:
<input field_type="text" name="myinputdield" id="myinputdield" value="" type="text" class="myinputdield">
How can I have the $data value auto-populated to the input field? I will appreciate any guide.

Print the database result in the value field
value="<\?php echo the_variable_that_holds_your_value ?>"
" type="text" class="myinputdield">

Related

How to update several fields in a single foreach loop?

I have a table with a list of users. Each one has assigned a checkbox. When the admin select some checkboxes my script saves some information into the database for the selected users.
Now, my issue is that beside that checkbox I want to have a text input type so the admin can leave a comment as well for that user. So, when the checkbox is selected and the input type has some data, the data gets saved as well.
This is what I've done so far (besides the obvious issues with security, that I haven't taken into account yet):
My list is generated by a loop for each user:
<input type=text name="infoAdicional" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">
I've taken the information and generated a foreach loop for the checkbox, but cannot get the additional information from the text field to get saved (it does update other values:
$userID = $_POST['enviar'];
$infoAdicional = $_POST['infoAdicional'];
foreach ($userID as $id => $email) {
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$infoAdicional'
WHERE userID = '$id'
AND email = '$email'
";
...
}
I think that's because $infoAdicional = $_POST['infoAdicional']; should be inside the loop, but just inserting it inside it, gets every user with a selected checkbox to have the same additional information, it does repeat itself.
It doesn't matter if you put the variable $infoAdicional inside the loop or not. The thing is that the last input field with the name overwrites all and therefore you will only have the note of the last user for all. What you need to change is, to make usage of the [] name syntax as you did it with the checkbox.
So your name attribute of the notes field would look like this name="infoAdicional['.$x['userID'].']" and in the loop you would make the assignment of infoAdicional[USERID] to $infoAdicional.
So your code would look like this
$userID = $_POST['enviar'];
foreach ($userID as $id => $email) {
$infoAdicional = $_POST['infoAdicional'][$id];
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$infoAdicional'
WHERE userID = '$id'
AND email = '$email'
";
...
}
And your HTML code
<input type=text name="infoAdicional['.$x['userID'].']" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">
Change your input parameters to:
<input type=text name="enviar['.$x['userID'].']['infoAdicional']" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']['email']" type="checkbox" value="'.$x['userEmail'].'">
So your data will stick to specific user. Then your loop will be like this:
$userInfo = $_POST['enviar']; //Info here, right?
foreach ($userInfo as $userId => $info) {
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$info['infoAdicional']'
WHERE userID = '$userId '
AND email = '$info['email']'
";
...
}
I've saved your syntax as it's your job to fill it with prepared statements etc.

How can I query a database based on a user text input?

So I am creating a Lorem Ipsum generator and I am stuck.
I have created a table called "wutangsoldiers", which contains the id of the user, their name, and each row has a different lyric. So far I have this:
$id = get_the_ID();
global $wpdb;
$lyrics = $wpdb->get_results("SELECT * FROM `wutangsoliders` WHERE `name` = '$id' ");
Inside of the generated text div, I have
<?php foreach ($lyrics as $lyrics) {
?>
<p><?php echo $lyrics->text;?></p>
<?php } ?>
How would I limit the number of "lyrics" shown based what the user inputs in <input type="submit" id="blaow" name="blaow">
To get the ID of the user based on a (I assume a text Input) I also assume that you are using HTTP POST METHOD ($_POST)
This is the User Value
<form>
<input type="text" value="1" name="user_value">
<input type="submit" id="blaow" name="blaow">
</form>
This is how to get the value
if(isset($_POST['blaow']){ // if the input has been pressed
$idUser = $_POST['user_value']; // the value sent from the HTML above
$lyrics = $wpdb->get_results("SELECT * FROM `wutangsoliders` WHERE `name` = '$idUser' ");
foreach ($lyrics as $lyrics) {
print "<p>".$lyrics->text."</p>";
}
}
Just get the user input limit that
$userinput = $_GET['lyrics_limit'];
Then put it in sql query
$lyrics = $wpdb->get_results("SELECT * FROMwutangsolidersWHEREname= '$id' limit '$userinput' " );
Then you will get only according to the input by user.

Open a form by id

I would like to open a form using a PHP URL by id. The URL looks like this.
http://localhost/application/workordersystem/woformEditor.php?woid=4
And receiving the id into PostgreSQL like this.
if (isset($_GET['woid']))
{
$query = "SELECT * FROM orders WHERE woid='$woid'";
$result = pg_query($query) or die(pg_error());
$row = pg_fetch_assoc($result);
}
I need the forms input fields to be filled with database data by the id in the database. What am I missing?
<input type="text" name="status" id="status" value="<?php echo $row['status']; ?>" />
Try debugging like so
echo print_r($row);
Additionally, you might want to add a limit. Tell us what you get.
$query = "SELECT * FROM orders WHERE woid='$woid' LIMIT 1";
But you should review the data structure returned by pg_fetch_assoc($result);
You'll want to map the keys you need to the input fields which should be revealed (or anomalies revealed) via the print_r function.

PHP MySQL - How easy way to update the database when one or more fields value changed

I have a little problem on database update activity.
Case study:
I created a form with PHP editing, and perform queries to retrieve the value of a record that wants to be updated. Excerpts of the script:
<?php
$row = mysql_fetch_assoc(mysql_query("SELECT id, field_1, field_2 FROM mytable WHERE id = $editid"));
?>
...
<form action="" method="post">
FIELD 1 <input type = "text" name = "f1v" value = "<? Php echo $ row ['field_1'];?>" />
FIELD 2 <input type = "text" name = "f2v" value = "<? Php echo $ row ['field_2'];?>" />
<input type="submit" />
</form>
....
// When the form posted
if ($_POST)
{
$f1v = $ _POST['f1v'];
$f2v = $ _POST['f2v'];
mysql_query("UPDATE mytable SET field_1 = '$f1v', field_2 = '$f2v' WHERE id = $editid") or die ();
// Redirect form
}
In this case I want when the form submited, there are activities to check whether there is a change in one or more fields values. Its logic approximately like this:
if ($ _POST)
{
// Compare
if the submitted value is different from the existing value in the record
{
Updated record
}
else
{
Do not update record
}
// Redirect form
}
Do you have any easy way to do it? Thank you for your help.
Don't bother checking. Just make sure the entry is valid and throw it in.
Keep two hidden fields with current values of the fields. After submitting the form check whether submitted values are different from the hidden field values.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories