How to fetch $POST data and put in database - php

Hi i have a simple form that uploads files and i want to get the id value using $POST and put in the database but my code is incorrect. Here is my code. I just want to ask if im doing the passing and fetching of $POST correctly? thanks
echo "<form action='process.php' method='post' enctype='multipart/form-data' id='uploadfile'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<select name='selectedValue'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option name="id" value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "Choose a file to Upload:";
echo "<input name='uploadedfile' type='file' /> <br/>";
echo '<input type="submit" name="submit" value="Upload">';
echo "</form>";
Here is the process.php file.
if(isset($_POST['selectedValue']))
{
$selectedValue = $_POST['id'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO sample_table ('user_id') VALUES ('$_POST[id]')"
$db->setQuery($query);
$result = $db->execute();
}

echo "<form action='process.php' method='post' enctype='multipart/form-data' id='uploadfile'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<select name='id'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "Choose a file to Upload:";
echo "<input name='uploadedfile' type='file' /> <br/>";
echo '<input type="submit" name="submit" value="Upload">';
echo "</form>";
process.php
if(isset($_POST['id']))
{
$selectedValue = $_POST['id'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO sample_table ('user_id') VALUES ('$selectedValue')";
$db->setQuery($query);
$result = $db->execute();
}
Okay. So you had some problems, you've set the "name" on the options, which is wrong, you have to set that on the .
Second, you missed a semicolon at the end on $query.
And last, i've chaged to check if the a value has been chosed from the dropdown and to set selectedValue to that, and use that in the query.

Related

PHP rows send 1 mySQLi record to form for edit [duplicate]

I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:
THE FORM
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
UPDATE QUERY
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}
Since you have multiple html fields with same names, you have to submit them as an arrays:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
After submitted, loop through any array variable like
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}

Post form and update multiple rows with mysql

I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:
THE FORM
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
UPDATE QUERY
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}
Since you have multiple html fields with same names, you have to submit them as an arrays:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
After submitted, loop through any array variable like
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}

php multiple search textbox with one submit button

i would like to know how can i make a multiple search criteria with 2 or more textboxes and only one submit button.
my script is:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE nume= '{$search_term}' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
and my results page that shows after search page:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE nume= '{$search_term}'";
}
echo "<center>\n";
echo "<table border='1'>";
echo "<thead>";
echo "<tr><th>Id</th>";
echo "<th>Nume</th>";
echo "<th>Localitate</th>";
echo "<th>Judet</th>";
echo "<th>Sector Financiar</th>";
echo "<th>Link</th></tr>";
echo "</thead>";
$rst = mysql_query($sql);
while($a_row = mysql_fetch_assoc($rst)) {
echo "<tr>";
echo "<td>"; echo $a_row['id']; echo "</td>";
echo "<td>"; echo $a_row['nume']; echo "</td>";
echo "<td>"; echo $a_row['localitate']; echo "</td>";
echo "<td>"; echo $a_row['judet']; echo "</td>";
echo "<td>"; echo $a_row['sector_financiar']; echo "</td>";
echo "<td>"; echo "<a href='results.php?id={$a_row['id']}'>{$a_row['link']}</a>" ; echo "</td>";echo "</tr>";
echo "</table>";
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term_by_Cauta = mysql_real_escape_string($_POST['search_box_1']);
$search_term_by_localitate = mysql_real_escape_string($_POST['search_box_2']);
//If you want both search mandatory, use "AND" Operator otherwise use "OR". If you want approximate search use "LIKE" Operator in bellow SQL
$sql .= " WHERE nume= '{$search_term_by_Cauta }' OR localitate = '{$search_term_by_localitate }' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box_1' />";
echo "<h3>localitate:</h3> <input type='text' name='search_box_2' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
Well you need another search box:
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box1' /><input type='text' name='search_box2' />";
And you need to use that value in your SQL:
if (isset($_POST['search'])) {
$search_term1 = mysql_real_escape_string($_POST['search_box1']);
$search_term2 = mysql_real_escape_string($_POST['search_box2']);
$sql .= " WHERE nume= '{$search_term1}' OR nume= '{$search_term2}'";
}
But you will have to do some thinking about how the search should work, is it supposed to match exactly one OR the other? If you want the text to contain instead of exactly match, you can use the syntax nume LIKE '%searchword%'
Use mysqli instead of mysql, which is depreciated. By PHP, something like this;
<form method='post'>
<input type='hidden' name='srch' val='1'>
Search Type1: <input type='text' name='s1'>
<br>
Search Type2: <input type='text' name='s2'>
<button>Submit</button>
</form>
<?php
if(isset($_POST['srch']))
{
if(!empty($_POST['s1']))$search = $_POST['s1'];
else if(!empty($_POST['s2']))$search = $_POST['s2'];
else die ('No criteria entered');
rest of your code...
}
?>
Also see functions like mysqli_real_escape for security reasons.

Set select option using php when reloading the same page

I have a php select populated and given a matching value by using php to loop through the results of a sql query.
$result = mysqli_query($con, "select * from course")
echo "<form action='' method='post'>";
echo "<select name='CourseSelect'>";
echo "<option value='0'> - Select Course - </option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['Title'] ." '>" . $row['Title'] . "</option>";
}
echo "</select>";
echo "<input name='SubmitCourse' type='submit'>";
echo "</form>";
That gives me a drop down list populated with all course titles,
upon submission I can access the selected value using $_POST['CourseSelect'];
However the drop down (select) resets itself to the default value when the page reloads.
How can I keep that option selected using php?
I know that I can use the selected keyword inside of an a select option to make that option the default selected option.
for example the second option would be selected when loading the page:
<select>
<option>One</option>
<option selected>Two</option>
<option>Three</option>
</select>
You can make it simple as
while($row = mysqli_fetch_array($result))
{
$select = '';
if( isset($_POST['CourseSelect']) && $_POST['CourseSelect'] == $row['Title'] ) $select = 'SELECTED';
echo "<option value='".$row['Title']."' ".$select.">" . $row['Title'] . "</option>";
}
you can use like below..
$result = mysqli_query($con, "select * from course");
$selected = "";
echo "<form action='' method='post'>";
echo "<select name='CourseSelect'>";
echo "<option value='0'> - Select Course - </option>";
while($row = mysqli_fetch_array($result))
{
$selected = $row['Title'] == $_REQUEST['CourseSelect'] ? "Selected" : "";
echo "<option value='" . $row['Title'] ." ' $selected>" . $row['Title'] . "</option>";
}
echo "</select>";
echo "<input name='SubmitCourse' type='submit'>";
echo "</form>";
try this:
echo "<option value='0'> - Select Course - </option>";
while($row = mysqli_fetch_array($result))
{
$selected = $_POST['CourseSelect'] == $row['Title'] ? 'selected' : '';
echo "<option value='{$row['Title']}' {$selected}>{$row['Title']}</option>";
}
you can do like this
echo "<form action='' method='post'>";
echo "<select name='CourseSelect'>";
if( isset($_POST['CourseSelect']) && $_POST['CourseSelect'] != "0")
{
echo "<option >".$_POST['CourseSelect']."</option>";
}
else
{
echo "<option value='0'> - Select Course - </option>";
}
while($row = mysqli_fetch_array($result))
{
if( isset($_POST['CourseSelect']) && $_POST['CourseSelect'] != $row['Title'])
echo "<option value='" . $row['Title'] ." '>" . $row['Title'] . "</option>";
}
echo "</select>";
echo "<input name='SubmitCourse' type='submit'>";
echo "</form>";
PHP Function
# select box
/*
Example:
Parameter 1:
$options[1] = 'Course 1';
$options[2] = 'Course 2';
$options[3] = 'Course 3';
Parameter 2:
$selectedOption = 2; The dropdown need to be selected
*/
function buildOptions($options, $selectedOption)
{
foreach ($options as $value => $text)
{
if ($value == $selectedOption)
{
$Return .='<option value="'.$value.'" selected="selected">'.stripslashes($text).'</option>';
}
else
{
$Return .='<option value="'.$value.'">'.stripslashes($text).'</option>';
}
}
return $Return;
}
Function Call
$result = mysqli_query($con, "select * from course");
while ($row = mysqli_fetch_array($result))
{
$UniqueId = $row['Title'];
$Value = $row['Title'];
$optionsArray[$UniqueId] = $Value; // Store the values into an array
}
$CourseSelect = isset($_POST['CourseSelect']) ? $_POST['CourseSelect'] : '0';
echo "<form action='' method='post'>";
echo "<select name='CourseSelect'>";
echo "<option value='0'> - Select Course - </option>";
echo buildOptions($optionsArray, $CourseSelect);
echo "</select>";
echo "<input name='SubmitCourse' type='submit'>";
echo "</form>";
Notes
You can use buildOptions() for all of your projects to display select box. I have been using this for years.

MySQLi Update Record via Form loaded from PHP and SQL. Database wont update

I am required to create a drop down box which gathers the records from a database to populate the drop down. When one of the values is selected, a form is to be displayed which contains the data relating to the value selected.
The form is to have the function of showing the selected data, but also to update the record in the database when filled out and Submit.
I have created a php file to try and accomplish this, but Im getting errors such as undefined index and unknown column.
I am only new to PHP so this is a big task for me. Could someone have a look at my code and inform me if there are any errors.
Ive been trying to piece code together here and there from the net but its been tricky trying to get it all to work.
I am not getting any errors now after some tweaking, but the record wont update. I get a 'record updated successfully' message but the record isn't updated.
I am pretty sure the lack of a record update is coming down to the ID not getting collected properly via the $q=$row["BearId"] but if I use $q=$_GET["q"] I get nothing but errors. I am not completely positive this is the problem though, that is why Im asking the question here.
I would appreciate any help that you can give. Ive gotten so far with this thing and yet I cant get it to update the record.
EDIT: I have pinpointed the problem down to the id in
$sql = "UPDATE //snip WHERE BearId = '$q'";
$q=$row["BearId"];
If I manually change BearId to equal '1' then the record is updated.
updatebears.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Bears</title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvalues.php?q="+str,true);
xmlhttp.send();
}
</script>
<style>
// style elements
</style>
</head>
<body>
<h1>Update Bears</h1>
Select a Bear:
<br />
<select name="bears" onchange="showUser(this.value)">
<option value="">Select a BearId</option>
<?php
$query = "SELECT * FROM bears";
$mysqli = new mysqli('localhost','User','123','bears');
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
echo '<option value="'.$row["BearId"].'">'.$row["BearId"].'</option>';
?>
</select>
<br />
<?php
$q=$row["BearId"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if(array_key_exists('_submit_check', $_POST))
{
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$q'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<br />
<div id="result"></div>
<br />
Click here to Visit Task 2 (Insert Bears) | Click here to Visit Task 3 (Display Bears)
</body>
</html>
getvalues.php
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}
?>
Thanks for the help.
I believe what you need to do is create a hidden input type for the BearId within the getvalues.php file. That way when your form performs the post you can get the BearId from the post as opposed to trying to get it from the $row['BearId']. I'm fairly certain $row['BearId'] is not the same $row['BearId'] that the user selected when he first goes to the getvalues.php form. Have you tried printing $row['BearId'] to html to verify it's a legitimate value?
if(array_key_exists('_submit_check', $_POST))
{
$id = $_POST['BearId']
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$id'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<h1>getvalues.php</h1>
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo <input type="hidden" name="BearId" value='".$q."'>
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}

Categories