PHP and dropdown insert error - php

Hello I want to insert in a table the values selected from a dropdown menu and values from a user that was previosly created . When I do the insert the only values that get inserted into the tables area the ones from the drop down list. But the other values dont get inserted. Please help me. Here is the code.
$query= "INSERT INTO employee (UserName, Password, Name, LastName, " .
"Email, Phone, Classification_ClassificationID) VALUES" .
" ('$user1', SHA('$password1'),'$name', '$lastname', '$email', " .
" '$phone_number', '$classification_id')";
queryMysql($query);
echo '<p>Account Created.</p>';
echo $user1;
}
echo '<h1> Grupo Asignado:</h1>' ;
if (isset ($_POST['submit'])){
foreach ($_POST['toinsert'] as $insert_id) {
$query = "INSERT INTO groupusers (GroupsID, Employee_UserName) Values ('$insert_id', '$user1')" ;
queryMysql($query);
echo mysql_num_rows($result);
echo '<br />';
}
}
$query = "SELECT * FROM employeegroups";
$result = queryMysql($query);
while ($row = mysql_fetch_array($result)) {
echo '<input type="checkbox" value="' .$row['GroupsID'] . '" name="toinsert[]" />';
echo $row['GroupName'];
echo '<br />';
}
echo '<input type="submit" name="submit" value="Insert" />';
echo '</form>';
echo '</body>';
echo '</html>';
?>

queryMysql($query);
echo mysql_num_rows($result);
Where are you setting this $result? It's not explicity passed back from your queryMysql() function, so either it's unset at this point, or it's a global variable (bad idea).
As well, have you checked that the queries are actually executing? The mysql query functions return boolean FALSE if the query fails. If you're assuming they succeeded and proceed in your code, you'd end up with the symptoms you have.

Related

getting plain array text when updating mysql record

so i have table with fields like this, i want to be able to edit each username/email etc if check box selected.
echo '<td><input type=checkbox name=checkbox[] value='. $row['Id'] .' ></td>';
echo '<td><input type=text name=username[] value='. $row['username'] .' ></td>';
echo '<td><input type=text name=email[] value='. $row['email'] .' ></td>';
echo '<td><input type=text name=adress[] value='. $row['adress'] .' ></td>';
and this is my script, i get array plain text as result from each input, btw Im using query for email only to test first
if(isset($_POST['edit']))
{
if(isset($_POST['checkbox'])) {
$id_array = $_POST['checkbox'];
$id_count = count($_POST['checkbox']);
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = ("UPDATE members SET email = '". $_POST['email'] ."' WHERE ID = '". $id ."'");
$result = $conn->query($query);
if($result) {
echo "ok";
}
else {
echo "<br><br>Error: " . $conn->error;
}
}
}
}
First off, you are vulnerable to sql injection attacks. Enjoy having your server pwn3d.
Secondly, you're stuffing your POST array directly into the query, which is incorrect. Since you're using the [] naming hack in the form fields, $_POST['email'] is going to be an ARRAY of values from your form, and you need something more like
.... VALUES ('$_POST[email][$i]', ...)
^^^^
(note the extra array index) to access the individual values in that sub-array.
Remember, for PHP, using an array in a string context gives you the literal word Array, and not the array's contents:
$foo = array(1,2,3);
echo "$foo"; // outputs 'Array'
echo "$foo[1]"; // outputs '2'

Inserting values from multiple checkboxes and textfields

I am a beginner in PHP.I am stuck with a problem. The idea is that I have to assign actors to a selected movie and add a role for each. I need to pick several values from the list and add a description for each via texfields. My code adds all the checked values to the database, but it makes a mess with the values from the textfields, the checked values don't match with the description. I would be really grateful for your help!
My code:
Form:
<?php
$sqlquery = "SELECT artistId, firstname, lastname from $artists order by 2";
$result = mysqli_query($connect, $sqlquery);
if($result) {
echo "<table class=\"addactor\">";
echo "<tr>
<td id=\"text\" colspan=\"2\"><h3>Assign an actor to the movie</h3></td>
</tr>";
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[]\"/></td>";
echo "</tr>";
}
echo "<tr><td align=\"right\"><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Add\"></td><td><input type=\"reset\" name=\"reset\" id=\"reset\" value=\"Reset\"></td></tr></table>;";
}
print '</table>';
The connection to the database is in another file, which is included here.
The second part:
if($_POST) {
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
$len = sizeof($checkbox);
for($i = 0; $i < $len; $i++) {
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $checkbox[$i] . "', '" . $_POST['moviecode'] . "', '" . $txt[$i] . "')";
mysqli_query($connect, $sqlqr);
}
$query = "INSERT INTO $movies(movieCode, title, dateOfIssue,category, description, image) VALUES ('" . $_POST['moviecode'] . "', '" . $_POST['title'] . "', '" . $_POST['dateofissue'] . "','" . $_POST['category'] . "', '" . $_POST['desc'] . "', '" . $_POST['image1'] . "')";
mysqli_query($connect, $query);
if(mysqli_query($connect, $query) || mysqli_query($connect, $sqlqr)) {
echo "<h4>1 record added</h4>";
}
else {
die('Error: ' . mysqli_error($connect));
}
print '</form>';
}
Unchecked values are not submitted and checkbox quantity not same with textbox.
You should give input name array same keys :
$i = 0;
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[".$i."]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[".$i."]\"/></td>";
echo "</tr>";
$i++;
}
Use also this code:
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
foreach ($checkbox as $key => $value)
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $value . "', '" . $_POST['moviecode'] . "', '" . $txt[$key] . "')";
mysqli_query($connect, $sqlqr);
}
use mysql_escape_string($_POST['']) instead of the every field $_POST[''] in inside the mysqlquery.
As documented under 17.2.1 Control types:
When a form is submitted, only "on" checkbox controls can become successful.
In other words, the browser will only submit those checkbox controls that have been 'checked', yet will submit every textbox control irrespective of the status of the checkbox control with which you intended it to be associated.
Therefore, unless all checkbox controls were checked, the arrays $_POST['checkbox'] and $_POST['textbox'] created by PHP from the form submission will contain different numbers of elements—and, consequently, those with any given index may not match.
There are two ways of resolving this:
one can use client-side scripting to disable the textbox if the corresponding checkbox is unchecked: this will prevent the browser from submitting the textbox and, accordingly, the arrays in PHP will be aligned again (however note that this solution depends upon the availability of client-side script—you will have to test for and handle cases where such scripting is unavailable); or
one can give the controls explicit indexes to ensure that they are always aligned.
You also really ought to read up on proper string escaping (and how failure to do so exposes your application both to bugs and commonly exploited attack vectors): I thoroughly recommend #deceze's blog article, The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
In particular, as he describes in his article, you should ensure that you escape any HTML in your variables before transmission to the browser (in order to prevent XSS attacks and bugs where the text to be output contains characters that have special meaning in HTML, for example <):
$result = mysqli_query($connect, "
SELECT artistId, CONCAT(firstname, ' ', lastname) AS fullname
FROM $artists
ORDER BY firstname
");
if ($result) {
echo '
<table class="addactor">
<tr>
<td id="text" colspan="2"><h3>Assign an actor to the movie</h3></td>
</tr>';
$i = 0;
while ($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '
<tr>
<td>
<input type="checkbox"
name="checkbox[',$i,']"
value="', htmlentities($sqlRow['artistId']), '"
/>', htmlentities($sqlRow['fullname']), '
</td><td>
<input type="text" name="textbox[',$i,']"/>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td align="right">
<input type="submit" name="submit" id="submit" value="Add">
</td><td>
<input type="reset" name="reset" id="reset" value="Reset">
</td>
</tr>
</table>';
}
Also, concatenating unescaped strings supplied by the user directly into your SQL not only makes you vulnerable to SQL injection attack, but furthermore introduces bugs where the strings contain characters that have special meaning within SQL string literals (for example ').
The solution is to prepare SQL statements with placeholders for parameters that get subsituted with your variables upon command execution; this also provides a performance boost since the statements need only be prepared once irrespective of the number of times that they are executed:
if ($_POST) {
$stmt = mysqli_prepare($connect, "
INSERT INTO $movies
(movieCode, title, dateOfIssue, category, description, image)
VALUES
(?, ?, ?, ?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'ssssss',
$_POST['moviecode'],
$_POST['title'],
$_POST['dateofissue'],
$_POST['category'],
$_POST['desc'],
$_POST['image1']
);
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
$stmt = mysqli_prepare($connect, "
INSERT INTO $role
(artistId, movieCode, Description)
VALUES
(?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'sss',
$checkbox,
$_POST['moviecode'],
$description
);
foreach ($_POST['checkbox'] as $i => $checkbox) {
$description = $_POST['textbox' ][$i];
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
}
echo '<h4>1 record added</h4></form>';
}

how to get items from mysql database added to the page with a checkbox for each item?

I need to write a function that does two things. It pulls a query from a mysql database and for each row found display the items of that row (There are 5 fields in the table id, title, description, timestamp, and a boolean). For each item displayed I need to have a checkbox displayed that if a user clicks the boolean is changed from off to on.
Please take this with a pinch of salt, I have not gone into any sort of security, and I'm sure there are much nicer ways but in the short time I had this might help you make a start.
<?php
$query = " SELECT id, title, description, timestamp, checkbox FROM database WHERE x = y";
$stmt = $db->prepare($query);
$stmt->execute();
echo '<form action="">';
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
$id =$row['id'];
$title =$row['title'];
$description =$row['description'];
$timestamp =$row['timestamp'];
$checkBox =$row['checkBox'];
echo 'ID: ', $id;
echo '<br>';
echo 'Title: ', $title;
echo '<br>';
echo 'Desc: ', $description;
echo '<br>';
echo 'Time: ', $timestamp;
echo '<br>';
if (checkbox == true){
echo 'Check <input type="checkbox" name="vehicle" value="$id" checked="checked">';
}else{
echo 'Check <input type="checkbox" name="vehicle" value="$id">';
}
}
echo '</form>';
?>

Display checkbox values in HTML after select, submit and email results from process.php

I have a checklist that's broken down into days, stage, timeShow, and bandName. I am displaying the options from a database with this script and I'm trying to display the results (and eventually email them) to the user on the 'process' page. How do I carry over the $result_x to the following page?
Here's an example of one of the 'blocks' for Saturday, Stage 1 and the value of the selection is the 'ID' of the row.
UPDATE- Part one is solved. Now looking to get the results sent to an email address input by the user.
FORM SOLUTION- 'Selection.php'
$sql_Sat1 = "SELECT * FROM bandSched WHERE day='saturday' AND stage='stage 1'";
mysql_query($sql_Sat1);
$result_Sat1 = mysql_query($sql_Sat1);
while($row = mysql_fetch_array($result_Sat1))
{
echo "<ul><li>";
echo'<input type="checkbox" name="id[]" value="'.$row['id'].' " id="bandSched_' . $row['id'] . '" />';
echo '<label for="bandSched_' . $row['id'] . '">' . $row['timeShow']." ".$row['bandName'] . '</label>';
echo "</li></ul>";
}
SOLUTION- 'process.php'
if ( ! empty($_POST['id']))
{ foreach($_POST['id'] as $key => $id) { $_POST['id'][$key] = mysql_real_escape_string($_POST['id'][$key]); }
$in = implode(', ', $_POST['id']);
$sql_Sat2 = "SELECT * FROM bandSched WHERE id IN ($in) ORDER BY FIELD(id, $in)";
$result = mysql_query($sql_Sat2) or die('MySQL Error ' . mysql_errno() . ': ' . mysql_error());
}
if ( ! isset($result))
{
echo 'You did not select anything';
}
else
{
while ($row=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>". $row['timeShow'] ."</td><td>" . $row['bandName'] . "</td>";
echo "</tr>";
}
}
Unless you have the attribute checked="checked" in your <input type="checkbox" />, the value will not be sent with the form data.
Try this:
echo '<input type="checkbox" value="' . $row['id'] .'"name="selected" checked="checked" />';
Does this solve the problem?
Carrying data from page to page can either be done with Sessions, Cookies, or posting hidden form elements containing the data.
Sessions provide you the data, but you still need to make a valid query. The only thing that sessions do are store data on the server. They do not keep any of the program execution, variables, etc.
Your error message is telling you that mysql_fetch_array was not supplied a MYSQL result resource (and it wasn't you supplied it an integer of the id value). The query will not be remembered across the session.
Also, mysql_* is deprecated, use PDO or mysqli.

print passes values

i am using insert into db(fname,lname) values ('$fname','$lname')
command i want that when this query passes on the nest page it show me which fname and which lname is passed or added like this statement
Following recorded is updated in database successfully
first name = abc
last name = xyz
Store the query in a variable, execute and print it out:
$query = "insert into db(fname,lname) values ('$fname','$lname')";
mysql_query($query);
echo $query;
Or, if you want to print just the variables, why can't you just do:
echo 'firstname: '.$fname.' ';
echo 'lastname: '.$lname;
If this is not what you needed, please clarify your question.
$query = "insert into db(fname,lname) values ('$fname','$lname')";
if(mysql_query($query))
{
echo "Following recorded is updated in database successfully\n";
echo "first name = $fname \n";
echo "last name = $lname \n";
}

Categories