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>
Related
I am trying to figure out mysqli (I am just a starting scripter). I created the following script to grab 3 different values from my database. And it prints it on the screen in different textareas and input fields.
What I want to be able to do is when I press the update button that it'll update the records in the database for the form where the button is attached to.
Can anyone give me some tips on how to achieve something like that?
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$standaardtekstlabel = $mysqli->query("SELECT standaardtekst_label FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardtekstnl = $mysqli->query("SELECT standaardtekst_tekst FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardteksten = $mysqli->query("SELECT standaardtekst_tekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$label_Tekst = mysqli_fetch_row($standaardtekstlabel);
$EN_Tekst = mysqli_fetch_row($standaardteksten);
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $label_Tekst[0] . '>
<textarea name="standaardtekst_tekst">' . $NL_Tekst[0] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $EN_Tekst[0] . '</textarea>
<input type="submit" value="update">
</form>';
}
?>
First of all, there is absolutely 0.0 reason why you're using 3 queries for the information you're trying to get. You can simply have: $standaardtekst = $mysqli->query("SELECT standaardtekst_label,standaardtekst_tekst,standaardtekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
Now regarding your question that is now probably obsolete:
Make the names of the input like this: standaardtekst_tekst[] saving it in an array.
You also need to have a unique(auto increment) key in your database like: id and put it in every form. You can even use the value of this field in the name like this: standaardtekst_tekst[$id].
You could edit your code a bit to look something like this:
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$q = $mysqli->query("SELECT standaardtekst_id, standaardtekst_label,
standaardtekst_tekst, standaard_tekst_tekst_en
FROM Standaardteksten
WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$row = mysqli_fetch_row($q);
?>
<form action="" method="POST">
<input type="text" name="formData[<?= $row['id']; ?>][standaardtekst_label]" value="<?= $row['standaardtekst_label']; ?>">
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst]"><?= $row['standaardtekst_tekst']; ?></textarea>
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst_en]"><?= $row['standaardtekst_tekst_en']; ?></textarea>
<input type="submit" value="update">
</form>
<?php
}
?>
What I've done:
Made your 3 queries into a single query
Gave each form a unique id
Cleaned up the code a bit
This enables you to do the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formData'])) {
foreach ($_POST['formData'] as $id => $value) {
$stmt = $mysqli->query("UPDATE standaardtekst SET standaardtekst_label='".$value['standaadtekst_label']."', standaardtekst_tekst='".$value['standaardtekst_tekst']."', standaardtekst_tekst_en='".$value['standaardtekst_tekst_en']."' WHERE standaardtekst_id='".$id."'");
}
}
Thx for the help everyone. Everything is working right now.
This is the script i used to get it to work :-)
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$result = $mysqli->query("SELECT * FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$row_s = $result->fetch_assoc();
do{
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $row_s['standaardtekst_label'] . '>
<textarea name="standaardtekst_tekst">' . $row_s['standaardtekst_tekst'] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $row_s['standaardtekst_tekst_en'] . '</textarea>
<input type="text" name="standaardtekst_ID" value="'. $row_s['standaardtekst_ID'] .'"/>
<input type="submit" value="update">
</form>';
} while($row_s = $result->fetch_assoc());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['standaardtekst_ID']))
{
$updatesql= sprintf("UPDATE Standaardteksten SET standaardtekst_label='%s', standaardtekst_tekst='%s', standaardtekst_tekst_en='%s' WHERE standaardtekst_ID='%s'",
$_POST[standaardtekst_label],
$_POST[standaardtekst_tekst],
$_POST[standaardtekst_tekst_en],
$_POST[standaardtekst_ID]
);
$mysqli->query($updatesql);
echo "Het volgende wordt aangepast: <br />", "Label:", $_POST[standaardtekst_label], "<br />" , "NL tekst:", $_POST[standaardtekst_tekst], "<br />" , "EN tekst:", $_POST[standaardtekst_tekst_en];
echo "<meta http-equiv='refresh' content='1;url=/form.php'>";
}
?>
I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<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>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.
I have a table with no.of users
$listuser = mysql_query('SELECT id,firstname,lastname,approve FROM user');
echo '<form action="" method="post">';
echo '<table>
<tr><td>Name</td>
<td>AdminApprove</td>
</tr>';
while($row = mysql_fetch_assoc($listuser))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo '<tr>
<td><input type="hidden" name="id[]" value ='.$id.'></td>
<td>'.$firstname.''.$lastname.'</td>
<td><input type="checkbox" name="approve[]"></td>
</tr>';
}
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table></form>';
After submitting the form
$postedid = $_POST['id'];
$approve = isset($_POST['approve']) ? 1 : 0;
$approvestudent = 'UPDATE user SET approve = '.$approve.' WHERE id = '.$postedid.'';
$result_update = mysql_query($approvestudent);
I want to approve either one or more at a time for each student and the approved checkbox value need to store to the database either with 0 or 1
$_POST['id'] is array not a string or integer
You can use php serialize() function to convert array into string
$postedid = $_POST['id'];
$approve = $_POST['approve'];
should be
$postedid = serialize($_POST['id']);
$approve = serialize($_POST['approve']);
I'm using echo to sum up the results form a Table. Inside this echo, I place another echo to show all the results form another table. On this page I have an array, I want every item in that array, that is also in the result from the table, to be checked. I use the code below (remember: this code is inside another echo!), it's not functioning, why not?
<?php
$query = "SELECT * FROM profilestemp";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$merkenarray = unserialize($row[merken]);
echo "
A VERY BIG OTHER PART OF THE FORM....
<tr>
<td style=\width:150px;background-color:#a8c11f;padding:2px;\"><p style=\"color:White;font-weight:bold\"><b>Merken</b></p></td>
<td><div id=\"rubrieken\">
<?php
$sql = \"SELECT merknaam FROM merken\";
$result = mysql_query($sql);
while ($row2 = mysql_fetch_array($result)) {
if (isset($merkenarray) && is_array($merkenarray) && in_array($row2[merknaam], $merkenarray)) {
$checked = \"checked='checked'\";
}
else $checked = \"\";
echo \" <input \".$checked.\" type=\"checkbox\" name=\"merken[]\" value='\" . $row2[merknaam] . \"'> \" . $row2[merknaam] . \" <Br /> \";
}
?>
</div></td>
</tr>
}
?>
Instead of using echo in your function, have it return the string to be output. An example:
function functionName() {
return 'Some content to be output';
}
echo functionName();
Additionally, this will give your function more flexibility, as you might not want to echo the result every time, e.g:
function functionName() {
return 'Some content to be output';
}
// Write the result of functionName to a file
file_put_contents('content.txt', functionName());
Your code should look like this
<?php
$query = "SELECT * FROM profilestemp";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$merkenarray = unserialize($row[merken]);
?>
A VERY BIG OTHER PART OF THE FORM....
<tr>
<td style="width:150px;background-color:#a8c11f;padding:2px;"><p style="color:White;font-weight:bold"><b>Merken</b></p></td>
<td><div id="rubrieken">
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row2 = mysql_fetch_array($result)) {
if (isset($merkenarray) && is_array($merkenarray) && in_array($row2[merknaam], $merkenarray)) {
$checked = "checked='checked'";
}
else $checked = "";
echo " <input ".$checked." type="checkbox" name="merken[]" value='" . $row2[merknaam] . "'> " . $row2[merknaam] . " <Br /> ";
}
?>
</div></td>
</tr>
<?php }?>
Any ideas why the following code is not adding anything into the database once the user fills out the form? I'd really appreciate it.
Thank you!
if($_SESSION['loginSuccess']==1) {
// ============================================================
// = Create the table of current tasks stored in the database =
// ============================================================
$userID = $_SESSION['userID'];
$result = mysql_query("SELECT * FROM Tasks WHERE userID = '$userID'");
echo "<div id=\"draggable\" class=\"ui-widget-content\"><table border='5'><tr class=\"ui-widget-header\"><td><u>Task Name:</u></td><td><u>Class:</u></td><td><u>Due Date:</u></td><td><u>Task Type:</u></td></tr>";
echo $_SESSION['userID'];
while($row = mysql_fetch_array($result)) {
$taskName = $row[1];
$class = $row[2];
$taskDueDate = $row[3];
$taskType = $row[4];
echo "<tr><td>'$taskName'</td><td>'$class'</td><td>'$taskDueDate'</td><td>'$taskType'</td></tr>";
}
echo "</table>";
function addNewTask ($name, $class, $dueDate, $type) {
mysql_query("INSERT INTO Tasks VALUES ('$userID','$name', '$class', '$dueDate', '$type')");
}
if($_POST['taskName'] != NULL) {
addNewTask($_POST['taskName'], $_POST['class'], $_POST['dueDate'], $_POST['dueDate']);
}
?>
<!-- <img border="1" alt="New" src="/newTask.png" id="newTask" onmouseClick="showTaskField"/> -->
<p><form name="newTask" method="post" action="index.php" id="newTask"><br>
Task Name: <input name="taskName" type="text"> (necessary)<br>
Class: <input name="class" type="text"><Br>
Due Date: <input name="dueDate" type="text" id="datepicker"><Br>
Type:
<input type="submit"></p></div>
Try getting rid of the ' around the variables in the insert statement. If that does nothing echoing mysql_error().