Input Values and Select Return Data - php

I'm trying to create a webpage where the user can submit information that they know and select information they'd like returned. For example, if they know the ID number for their submission, they can enter it and ask for the returned values to be the ID number and product name.
The information that's being retrieved is stored in a MySQL database, and the html page is laid out with a select menu, text boxes, and checkboxes (so that the user can select a name or enter other information, and then use the checkboxes to select the other information they want returned).
Here's the relevant html:
<table><tr>
<form name="input" method="post" action="next.php">
<td width="120">Flowcell ID:<br />
<select name = "Flowcell_ID">
<option disabled="disabled" selected="selected">
Select...
</option>
<?php
$link = mysqli_connect("localhost","user","pass","db");
$query = "SELECT DISTINCT ID FROM table";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$id = $row['ID'];
echo "<option value=\"$id\">$id</option>";
}
mysqli_close($link);
?>
</select></td>
</tr><tr>
<td width="120">Name:<input type="text" name="Name" /></td>
</tr><tr>
<td width="120">Date:<input type="text" name="Date" /></td>
</tr><tr>
<td width="120">Group:<input type="text" name="Group" /></td>
</tr><tr>
<td width="120"><input type="checkbox" name="options[]" value="ID">ID</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Name">Name</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Date">Date</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Group">Group</input></td>
</tr></table>
The only php I have so far is:
$id = $_POST['ID'];
$name = $_POST['Name'];
$date = $_POST['Date'];
$group = $_POST['Group'];
How would I produce a MySQL query that looks like
SELECT [checked checkboxes] FROM table WHERE [information field] = [user-entered information]
?
Thanks!

You can build the query incrementally:
$fields = array(
'ID' => 'id',
'Name' => 'name',
'Date' => 'date',
'Group' => 'group',
);
$query = 'SELECT'; // Optional fields to be displayed may go here
$comma = ' '; // and if they do, start with $comma = ', ';
$where = array();
foreach($fields as $post => $mysql)
{
// here we have $post equal to 'ID', our POST field, and
// $mysql equal to, say, 'Id' -- the MySQL field name.
// Check whether options['ID'] is set. If so, we must get
// the _POST[ID] field and check its contents against "Id" field in DB.
if (in_array($post, $_POST['options']))
{
$query .= "$comma$mysql";
$comma = ', ';
// Add WHERE condition
$where[] = "$mysql = '" . mysql_real_escape_string($_POST[$post]) . "'";
}
}
// $comma, the separator between option fields, also doubles up as a check
// to see whether we have conditions.
// another possibility would be, "if (empty($where))"
if (' ' == $comma)
die("You must select at least one checkbox!");
$query .= ' FROM table WHERE ';
// Build WHERE condition
$query .= '(' . implode(' AND ', $where).')';
// Other conditions may go here (e.g. " AND record_valid = 1 ")
$query .= ';';

Related

Update the value from table in textbox BUT not updated the value in db?

I have listed all the data(Item, Category, Job, Hole(Hole is evaluating marks)) and I display the Hole(mark) in textbox filed.
I want to update the Hole(marks) after user change.
I list all the data using php
<?php
try{
$con = new PDO("mysql:host=localhost;dbname=gcmes", "root", "");
$sql = $con->query("SELECT * FROM details");
echo"<table class='info' align='center'>";
echo"<tr><td width='10'><b>No</b></td>
<td width='30'><b>Category</b></td>
<td width='50'><b>Job</b></td>
<td width='40'><b>Evaluate</b></td><tr>";
foreach($sql as $row) {
$Item = $row["Item"];
$Category = $row["Category"];
$Job = $row["Job"];
$Evaluate = $row["Hole 1"];
echo'
<tr>
<td>' . $Item . '</td>
<td>' . $Category . '</td>
<td>' . $Job . '</td>
<td><input type="input" name="Evaluate" id="Evaluate" value="' . $Evaluate . '">
</td>
</tr>
';
}
echo"</table></form>";
if(isset($_POST['Update_btn'])){
$Evaluate = $_POST["Hole 1"];
if(empty(Evaluate)){
echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>";
}
else{
$insert=$con->prepare("UPDATE details SET Evaluate=:Hole 1 WHERE Item=:Item");
$insert->bindParam(':Hole1',$Evaluate);
$insert->bindParam(":Item",$Item);
$insert->execute();
echo "<script type='text/javascript'>alert('Successful Updated ! ');
window.location.href = 'Hole 1.php';
</script>";
}//else
}//if add button
}//try
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>
The html code i just use to display button
<form id="form1" name="Hole 1" method="post" action="Hole 1.php">
<input name="Update_btn" type="image" id="Update_btn" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" value="submit" src="UpdateD.png" alt="submit Button" align="right">
</form>
The problem is will alert message successful updated BUT the value not update in my db. Why? what is the problem?
this is my interface
i want update the marks in textbox filed
I need to change the hole as a selection give the user choose which hole that need to update only, i set the hole have a drop-down menu list. How to dectect which hole?
i just add the code after <td>{$rowData['Frequency']}</td> (dn Fer answer)
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
Keep the following in mind:
I don't have the same environment as yours, so it might not work one
on one.
Spaces in database fieldNames and arrayKeys, etc. are discouraged. I
prefer to use lowerCamelCase, check if dB fieldNames match the code
below!
Read the comments I've placed in the code.
I didn't take psr coding, value validation or safety (sql injection), etc. in consideration. The code is to guide you, you should take these things in consideration yourself.
Hopefully getting you closer to your goals...
Update: The values of the Evaluate field of each row is now validated to be an integer in the range from 1 to 5.
<?php
//Initialize variables
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
//Because button type is 'image', we get parameters buttonName_x and buttonName_y
//from the browsers POST request when the form is sent.
if ($doUpdate) {
//Update button pressed.
//Initialize variables
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`hole1` = CASE `item` ';
foreach ($_POST['evaluate'] as $item => $hole1) {
//Get input value of each table row
if (filter_var($hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $item;
$stmtSetParams[] = $hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$item\' with a value of \'$hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="test.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info align-center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>No</b></th>
<th width="30"><b>Category</b></th>
<th width="50"><b>Job</b></th>
<th width="40"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
<tr>
<td>{$rowData['item']}</td>
<td>{$rowData['category']}</td>
<td>{$rowData['job']}</td>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="evaluate[{$rowData['item']}]" id="Evaluate" value="{$rowData['hole1']}"
min=1 max=5
>
</td>
</tr>
HTML;
}
?>
</table>
<!-- Attribute align is deprecated, define and use a class instead -->
<!-- Value attribute should not be specified -->
<input name="updateButton" type="image" id="Update_btn" src="http://via.placeholder.com/100x50/0000FF?text=Update"
alt="submit Button" class="align-right"
onmouseover="this.src='http://via.placeholder.com/100x50/00FF00?text=Update'"
onmouseout="this.src='http://via.placeholder.com/100x50/0000FF?text=Update'"
>
</form>

mysql query in a loop using left join with columns the same name

I am building a search form with multiple fields to search. Data is in 2 different tables depending on what you are searching for in each field.
I have a column that has the same name in each table. Because of this it obviously gives me the sql error of: Column 'state' in where clause is ambiguous
It would not be a problem if the form fields were not in a loop. I am new to php and this is trying me.
I have tried to use aliases in the SELECT for mysql but now i cant target them because it doesnt come through correctly.
Here is what i have for my form:
<form method="post" action="index.php">
<tr>
<td>Name:</td>
<td>
<input type="text" name="display_name" id="display_name" class="display_name tt-query" autocomplete="off" spellcheck="false" placeholder="Type name of person"></td>
</tr>
<tr>
<td>Service Type:</td>
<td><select name="service_name">
<option>
<?php
$query1 = "SELECT service_type FROM nfw_service_type ORDER BY id_num";
$result1 = mysqli_query($conn, $query1); #$num_results1 = mysqli_num_rows($result1);
?>
<?php /*Loop through each row and display records */
for($i=0; $i<$num_results1; $i++) { $row1 = mysqli_fetch_assoc($result1);
?>
<?php // echo 'Name' .$row['ssfullname'] . 'email' . $row['ssemail'] . "\n"; ?>
<option value="<?php print $row1['service_type']; ?>"><?php print $row1['service_type']; ?></option>
<?php // end loop
} ?>
</select></td>
</tr>
<tr>
<td>Suburb:</td>
<input type="text" name="suburb" id="suburb" class="suburb tt-query" autocomplete="off" spellcheck="false" placeholder="Type name of person"></td>
</tr>
<tr>
<td>State:</td>
<td>
<select name="usersstate2">
<option>
<option value="qld">QLD</option>
<option value="sa">SA</option>
<option value="nt">NT</option>
<option value="wa">WA</option>
<option value="vic">VIC</option>
<option value="tas">TAS</option>
<option value="act">ACT</option>
</select>
</td>
</tr>
<tr>
<td>Type:</td>
<td>
<select name="user_type">
<option>
<option value="franchise">Franchisee</option>
<option value="regional">Regional</option>
<option value="state">State</option>
<option value="national">National</option>
<option value="office">Headoffice Staff</option>
</select>
</td>
</tr>
<tr>
<td>Active:</td>
<td>
<select name="active1">
<option></option>
<option value="1">Active</option>
<option value="0">Not Active</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Search" /></td>
</tr>
</form>
And here is the code once the form is submitted:
<?php
// SEARCH
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('display_name', 'service_name', 'suburb', 'nfw_users.usersstate2', 'user_type', 'nfw_users.active1');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
$example = $_POST[$field];
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "`$field` LIKE '%{$example}%'";
}
// builds the query
$query = "SELECT
nfw_users.id_num,
nfw_users.display_name,
nfw_users.first,
nfw_users.last,
nfw_users.email,
nfw_users.mobile,
nfw_users.landline,
nfw_users.user_type,
nfw_users.suburb,
nfw_users.active AS active1,
nfw_users.state AS usersstate2,
nfw_services.state AS servicesstate3
FROM
nfw_users
left JOIN nfw_services ON nfw_services.user_id = nfw_users.id_num
LEFT JOIN nfw_service_areas ON nfw_service_areas.service_id = nfw_services.id_num ";
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' AND ', $conditions) ." GROUP BY nfw_users.id_num ORDER BY nfw_users.display_name"; // you can change to 'OR', but I suggest to apply the filters cumulative
}
}}
$result = mysql_query($query);
var_dump($query);
if (mysql_num_rows($result) > 0) {
while ($score = mysql_fetch_assoc($result)) {
$active1 = $score['active1'];
if ($active1=='1') {
$activeother = "<i class='fa fa-check' style='color:green;'></i>";
}
else {
$activeother = "<i class='fa fa-times' style='color:red;'></i>";
}
$content = "<tr><td>" . $score['display_name'] . "</td><td>" . $score['first'] . "</td><td>" . $score['last'] . " </td><td>" . $score['email'] . " </td><td> " . $score['mobile'] . " </td><td> " . $score['landline'] . "</td><td>$activeother</td><td> " . $score['user_type'] . "</td><td> " . date('d-m-Y', strtotime($score['date_join'])) . "</td><td class='invoicing-columns'><a class='btn btn-yellow' href='view-invoices.php?id=" . $score['id_num'] . "'><i class='fa fa-eye'></i></a></td><td class='invoicing-columns'><a class='btn btn-red' href='del-customers.php?id=" . $score['id_num'] . "' onclick='return check();' class='delete'><i class='fa fa-minus-circle'></i></a></td></tr>";
echo $content;
}
}
?>
Yes i do know one part isnt using sqli and i will fix that. :)
You are on the right track, but your implementation of alias names is a bit off. To assign an alias use the format sometable as somealiasname. Use an alias different than your table names (t1, t2, t4,etc. are common).
Try this:
//as long as you only use each attribute name once, you could do it like this:
$fields=array();
$fields['t1'] = array('display_name', 'service_name', 'suburb', 'state', 'user_type', 'active');
$fields['t2'] = array('some_other_field_in_t2','yet_another_field_in_t2');
$fields['t3'] = array('some_other_field_in_t3','yet_another_field_in_t3');
foreach($fields as $table=>$these_fields){
foreach($these_fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$example = $_POST[$field];
// TODO: don't forget to sanitize inputs
$conditions[] = "`$table`.`$field` LIKE '%{$example}%'";
}
}
}
$conditions[] = "t1.`$field` LIKE '%{$example}%'"; //for values are coming from t1 (nfw_users)
$conditions[] = "t2.`$field` LIKE '%{$example}%'"; //as long as all values are coming from t1 (nfw_users)
Alternatively, you could try this approach to map unique keys to a specific location if you want to pull data from columns in different tables that have the same column name:
$fields=array();
$fields['display_name']=array('table'=>'t1','attribute'=>'display_name');
$fields['service_name']=array('table'=>'t1','attribute'=>'service_name');
$fields['suburb']=array('table'=>'t1','attribute'=>'suburb');
$fields['state']=array('table'=>'t1','attribute'=>'state');
$fields['user_type']=array('table'=>'t1','attribute'=>'user_type');
$fields['active']=array('table'=>'t1','attribute'=>'active');
$fields['some_other_field_in_t2']=array('table'=>'t2','attribute'=>'some_other_field');
$fields['yet_another_field_in_t2']=array('table'=>'t2','attribute'=>'yet_another_field');
$fields['some_other_field_in_t3']=array('table'=>'t3','attribute'=>'some_other_field');
$fields['yet_another_field_in_t3']=array('table'=>'t3','attribute'=>'yet_another_field');
foreach($fields as $field=>$field_data){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$example = $_POST[$field];
// TODO: don't forget to sanitize inputs
$conditions[] = "`$field_data['table']`.`$field_data['attribute']` LIKE '%{$example}%'";
}
}
Either way....
$query = "SELECT
t1.id_num,
t1.display_name,
t1.first,
t1.last,
t1.email,
t1.mobile,
t1.landline,
t1.user_type,
t1.suburb,
t1.active AS active1,
t1.state AS usersstate2,
t2.state AS servicesstate3
FROM
nfw_users as t1
LEFT JOIN nfw_services as t2 ON t2.user_id = t1.id_num
LEFT JOIN nfw_service_areas as t3 ON t2.service_id = t1.id_num";
$query .= "WHERE " . implode (' AND ', $conditions) ." GROUP BY t1.id_num ORDER BY t1.display_name";
This page discusses aliases if you'd like more examples:
http://www.w3schools.com/sql/sql_alias.asp

Separate out array based on array data

I want to create a table for documents and allow users to select whether the document is required or not in relation to a task. I need it to check the current status of the document to see if it is already required and if it is mark the tick box as checked. There are currently 4 documents in the database and only 2 associations to 2 of the documents for this particular task.
When there is no association of a document to a task there will be no entry in the database to say that it is not associated it just simple will not be in that table.
The code I have currently will show checkboxes against those 2 documents which have associations however do not show any tick boxes at all for the ones that have no association. I would like it to still show the 3 check boxes, so that the user can change its association, but as default it should check not required. Currently It just shows no tick boxes at all. Below is the PHP snip. Please advise if you would like a screenshot or the DB dumps.
Any help would be greatly appreciated. I'm hoping its just been a long day and I am forgetting something simple.
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
while ($row4 = mysql_fetch_array($result4)) {
$requirement = $row4['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>';
So far I have just tried tweaking the requirement = with the final tick box. But as it is staying the same whether i use NULL ect - im guessing im missing something.
Kind Regards,
n00bstacker
You can use the following if statement to identify the situation and respond appropriately:
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
$_results = mysql_fetch_array($result4);
if (!$_results) {
<<<< OUTPUT THE CHECKBOXES/INPUTS YOU NEED >>>>
} else {
foreach ($_results as $result) {
$requirement = $result['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
Hope this helps!

Check a check box if it's value is in DB. PHP

I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.

Create input fields dynamically with values and column names from database

I create inputs using the information in the columns for example if a field is called about_content it outputs a label of About Content with an input field. This works fine for inserting however I want to use this code similarly to UPDATE and I want to display to users the current value of a field as entered in the database. For example if about_content = Hello World! I want the input value to reflect that. Is there a way of doing this dynamically?
<?php
require('dbc.php');
mysql_select_db($db);
$resultInput = mysql_query("SHOW COLUMNS FROM about WHERE Field NOT IN
('id', 'created', 'date_modified', 'last_modified', 'update', 'type', 'bodytext')
AND Field NOT REGEXP '_image'"); // selects only the columns I want
$result = mysql_query("SELECT * FROM about WHERE id=".$_GET['id']); // values I want to put into the values for <input>
while ($row = mysql_fetch_assoc ($result) && $column = mysql_num_rows ($resultInput)) {
foreach($row as $column => $value){
echo '<label>'.$column.'<input name="'.$column.'" type="input" value="'.$value.'"></label><br>';
}
}
?>
See the spot you've marked with an arrow? Instead of the string (1), set value to the appropriate database value you read in $result (not in $resultInput).
Here's how: use mysql_fetch_assoc for your SELECT query, not mysql_fetch_row. There will be only one row, so fetch it before you start generating the form. You'll then have a named array with the row values, and you can grab each field by name and put it in the form.
If you don't understand how to do that, check the php documentation for mysql_fetch_assoc.
And escape your $_GET['id'] like you were told in your last question. You're begging to be pwned!
See mysql_fetch_field.
if (mysql_num_rows($result) > 0) {
//loop creates inputs
//make $resultInput object to array.
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$meta = mysql_fetch_field($result, $i);
if(in_array($meta->name, $resultInput )){
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ',$meta->name)) .
'<br><input name="' . $meta->name .
'" type="text" class="input" value="$row[$meta->name]"><br></label></div>';
}
$i++;
}
}
<?php
include('db.php');
if (isset($_POST['btn'])) {
$dcolumn = $_POST['dyncolumns'];
$dvalue = $_POST['dynfields'];
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$query = "INSERT into addtable(name,mobile,address)VALUES('" . $name . "','" . $mobile . "','" . $address . "')";
$result = mysql_query($query)or die(mysql_error());
$id = mysql_insert_id();
if ($dcolumn) {
foreach ($dcolumn as $key => $value) {
$result1 = "show COLUMNS from addtable like '.$value.'";
$exists = mysql_query($result1)or die(mysql_error());
$data = mysql_fetch_assoc($exists);
if ($data==TRUE) {
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
} else {
$query1 = "ALTER TABLE addtable ADD $value varchar(45)";
$result2 = mysql_query($query1)or die(mysql_error());
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
$result = mysql_query($query)or die(mysql_error());
}
}
}
}
?>
<script>
function myFunction() {
var table = document.getElementById("insert");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<input type='text' name='dyncolumns[]'>";
cell2.innerHTML = "<input type='text' name='dynfields[]' >";
}
</script>
<html>
<body>
<form name="insert" method="post">
<table border="2" align="center" id="insert">
<tr>
<td>Name</td><td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Mobile</td><td><input type="text" name="mobile" maxlength="10"/></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="address" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn" value="submit"></td>
</tr>
</table>
<input type="button" onclick="myFunction()" name="add" value="Add">
Logout
</form>
</body>
</html>

Categories