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>';
}
Related
I'm creating a script where I'm getting information from a database and automatically importing it into a table using PHP and creating a form. In the form I'm naming the fields by whatever the data in they contain in the database. I'm having trouble in the values part of the query inserting the form values into the database because I'm not sure how to loop through and add all the input fields. How would I do this?
while ($aRow = mysql_fetch_assoc($aResult)) {
if ($aRow['correct'] == 1) {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
} else {
$tableString .= "<input name=". $qRow['questionID'] ."
type='radio'
>" .
$aRow['answerValue'] . "<br />";
}
$answer= [$aRow];
$question= [$qRow];
$student= [$username];
// Insert data into mysql
//$sql="INSERT INTO $userexam(answerID, questionID, userID)VALUES('$answer', '$question', '$student')";
//$result=mysql_query($sql);
$query = " INSERT INTO userexam (
answerID,
questionID,
userID)
VALUES ( '" . $_POST['/* answerID */'] . "', '" .
$_POST['/* questionID */'] . "', '" .
$_POST['/* userrole */'] . "')";
}
The Problem with radio buttons is: They are not send via $_POST if they are not checked. You need to "know" what radiobuttons exist and those who are not send with $_POST are not checked.
As for the looping:
You can give your radio buttons a "main" name in addition to your IDs:
<form method="POST">
<input type="radio" name="foo[23]">
<input type="radio" name="foo[45]">
<input type="submit" value="foo">
</form>
Take a look at the $_POST variable and you see that both radio buttons are within an array. You can use that array to iterate through all checked radio buttons.
And please start using PDO instead of mysql_ :)
Im using method post to send a mutliple input text form, i draw information from the database to after re insert the information which is inside input text:
echo "<CENTER><TABLE BORDER='0'>";
echo "<FORM METHOD='POST'>";
$sele_players = "SELECT nombre FROM JUGADORES WHERE NOM_EQUIPO='Aston villa'";
$sele_players = mysql_query( $sele_players , $link );
while( $row = #mysql_fetch_assoc( $sele_players ) )
{
$row['nombre'] = addslashes( $row['nombre'] );
echo "<TR><TD ALIGN='CENTER'>".$row['nombre']."</TD>";
echo "<TD><INPUT TYPE='TEXT' NAME='{$row['nombre']}'></TD></TR>";
}
echo "<TR><TD COLSPAN='2' ALIGN='CENTER'><INPUT TYPE='submit' NAME='send2' VALUE='INSERTAR' style='width:200px; height:60px' ></TD></CENTER></TR>";
ok here i get the names of players from database, then i use them for insert inside input text as his name, to after pick with array $_POST:
if( !empty( $_POST['send2'] ) )
{
foreach($_POST as $jugador => $points)
{
$jugador = str_replace( "__" ,". ", $jugador );
$jugador = str_replace( "_" ," ", $jugador );
if( $points == "" )
{
$points = "NULL";
}
$inser_jornada = "INSERT INTO JORNADA VALUES( '{$_GET['jornada']}','{$_GET['equipo']}', '$jugador', '$points', now() );";
So there is no problem with most of names, excluding N'Zogbia name or apostrophe names which is shown in $_POST array as 'N', i have tried adding slashes before send it through from but doesnt work, so i dont know how to get the complete name in post array, thats the main problem.
THanks forwarded!!
There are many things to point out here. But instead of that, I will try my best to be helpful.
Add your database entries using mysql_real_escape_string($variableName) to enter the content to the database. It will automatically escape such quotes and make it a little SQL Injection proof.
As it was mentioned before, your code "screams" help. There are lot of things to point out, but back to your answer: I think your problem is in the following line:
$inser_jornada = "INSERT INTO JORNADA VALUES( '{$_GET['jornada']}','{$_GET['equipo']}', '$jugador', '$points', now() );";
Try this instead:
$inser_jornada = 'INSERT INTO JORNADA VALUES( "' . $_GET['jornada'] . '", "' . $_GET['equipo'] . '", "' . $jugador . '", "' . $points . '", now() );';
I would really, really recommend that you run mysqli_real_escape_string() to all your input.
Good luck!
Okay so I'm making php that will pull every entry from a data base that matches the name you put in a textbox. so here is a image of the database
http://i.stack.imgur.com/LvmrM.png < screen shot of database
So if i where to put "DigitalNuke" in the textbox and hit the submit button I want only the rows that have "DigitalNuke" as the value in the second column "referrer"
<form ACTION="" METHOD=post>
<div class="input-append">
<input class="span2" id="youruser" type="text" name="youruser" placeholder="Your Username">
<button class="btn btn-success" type="submit">Retrive</button>
</div>
</form>
<?php
require_once 'connect.php';
$name = isset($_POST['youruser']);
$conn= mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname)or die(mysqli_error());
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
$result = mysqli_query($conn, $query1)
or die('Error querying the database: ');
echo '<table class="table table-bordered">';
echo '<caption>Your Referred Members</caption>' . '<thead><tr><th>ID</th>' . '<th>Username</th>' . '<th>Brigade</th>' . '<th>Faction</th>' . '<th>Activity</th>' . '</tr></thead>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='success'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['brigade'] . "</td><td>" . $row['faction'] . "</td><td>" . $row['activity'] ."</td></tr>";
}
?>
So as of now it doesn't do anything when I hit the submit button. Well it kind of works, except for instead of pulling the data from the table, it just puts id, username, brigade, faction, activity in each row of the generated table.
http://i.stack.imgur.com/XF71h.png < screen shot
Any help would be appreciated, if you need anything else let me know and i'll post it.
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
should be:
$query1 = "SELECT `id`, `referrer`, `username`, `brigade`, `faction`, `activity` FROM refmems WHERE referrer='$name'";
Also learn how to use prepared statements for MySQLi. Your code is open to SQL injection.
Your syntax is broken.
"SELECT id, referrer, username, brigade, faction, activity FROM refmems WHERE referrer='$name"
There is no closing single quote after $name, and the fields don't get quoted (or use backticks but it isn't necessary).
Also, you are asking for trouble. You've got user input with no validation/sanitization.
I have a form with a select box where the user can select pre-existing fields from a database:
<form action='' method='POST' autocomplete='off' enctype="multipart/form-data">
<p><strong>Title and Description:</strong></p>
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"1\">" . $row['title'] ." - " . $row['description'] . "</option>";
$uid = $row['uid'];
$title = $row['title'];
$desc = $row['description'];
}
?>
</select>
...
How can I send all three of those values (separately) to my postback for SQL?
if (isset($_POST['submitted'])) {
//Get params for prepared statements
$startDatec= date("Y-m-d H:i:s", strtotime($_POST['startEventDate']));
$endDatec= date("Y-m-d H:i:s", strtotime($_POST['endEventDate']));
$startTimec=$_POST['startTime'];
$endTimec=$_POST['endTime'];
$recurc=$_POST['recurrence'];
$finalc= date("Y-m-d H:i:s", strtotime($_POST['finalDate']));
...
I have no idea why you would need to send all three values back. Database Keys exist for the reason of being able to identify ALL fields in a record given just a single field, in this case I'm assuming uid. Passing that field alone would allow you to select the other fields in your postback before performing the operation that you intend.
However, it is possible using hidden form fields, although I don't advocate this approach.
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
$cacheArray = array(); // Used to store the information to be used below
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"" . $row['uid'] . "\">" . $row['title'] ." - " . $row['description'] . "</option>";
$cacheArray[] = $row;
}
?>
</select>
<?php
foreach($cacheArray as $k => $v) {
echo '<input type = "hidden" name = "title-' . $v['uid'] . '" value = "' . $v['title'] . '">';
echo '<input type = "hidden" name = "description' . $v['uid'] . '" value = "' . $v['description'] . '">';
}
?>
The hidden form fields will be present for all records in your tblFacilityHrs table. The names are made distinct by appending the uid to the name. You can determine what fields you are interested in in your postback by:
$_POST['title-'.$_POST['uidtitle']]
$_POST['description-'.$_POST['uidtitle']]
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.