The table deportes has 2 columns with 4 rows:
<?php
$sql = 'SELECT * FROM deportes';
$resul = mysqli_query($conexion, $sql);
$deportes = array();
while ($fila = mysqli_fetch_array($resul))
{
$deportes[] = $fila;
}
?>
The form with the select multiple options:
<select name="fan[]" multiple="multiple">
<?php
foreach ($deportes as $aficion)
{
echo "<option value='".$aficion['idD']."'";
echo " >{$aficion['nombreDep']} </option>\n";
}
?>
</select>
Get the values from the form
<?php
if (isset($_POST['fan']))
{
$sport = $_POST['fan'];
}
?>
Now this
<?php $sport = mysqli_real_escape_string($conexion, $sport); ?>
This way insert the values in another table
$idPersona = mysqli_insert_id($conexion);
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
And the result is i get the value "0" in the field idD from table mec
If you print_r your $_POST['fan'], you will see that this is array. To get every value of array you should iterate over it, with for or foreach:
$idPersona = mysqli_insert_id($conexion);
foreach ($_POST['fan'] as $sport) {
echo $sport; // you will see that now it is string
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
// execute your query
}
And of course you must move to prepared statements to protect your code from sql-injection. This question will give you a start.
Related
EDIT: IGNORE ANY SQL INJECTIONS OR VULNERABLE CODE STATEMENTS :D
(School Project).
I wish to create a insert form on my webpage where I can select an artist from a table, including a song from a table and combine them for an insert into a combined foreign key table.
I have managed to do selects and insert with only individual artist and song drop-downs on my web-page, but would wish for combining the two ID's from each table to combine them to a many to many relative table. But when I press the submit button nothing happens, and I'm a beginner and don't know if I'm missing any important bits of actually Posting the information.
For troubleshooting I have tried my code, and tested it. I see if I remove my code theres no problem, so the problem persists on the syntax I believe, as the first dropdown shows, alongside the second dropdown and submit button, but the problem is within the actual processing and SQL query part, where it never goes to the DB..
The problem:
As you can see below I have a the text Song Name appear with a drop-down menu in the bottom left corner including the Artist Name with a submit button. But my problem persists as the select and then insert from the two drop downs into the combined table does not work, it does not actually submit, I want it to post into the DB what can I do. But somethings off? I would appreciate any questions or help, this community is so amazing and wonderful to operate in!
Database
PHP
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl $sql
($conn->error.";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
</form>
<input type="submit" name="mangetilmange" value ="Submit">
change you code to this:
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
<input type="submit" name="mangetilmange" value ="Submit">
</form>
I am trying to embed a drop down list to an update page, it works fine but I am having problems with option selected part. When an option is shown it also duplicates it in the list.
Is there any way I can say if record is used do not use it again with PHP?
<?php
$sql = "SELECT TeamName, TeamID FROM tblTeam";
$result = mysql_query($sql);
$player_id = $_GET['id'];
$current_team = mysql_query("SELECT
tblteam.TeamID,
tblteam.TeamName,
tblplayer.PlayerID,
tblplayer.PlayerTeam,
tblplayer.PlayerName
FROM
tblplayer
INNER JOIN tblteam ON tblplayer.PlayerTeam = tblteam.TeamID
WHERE PlayerID = $player_id LIMIT 1 ");
$my_row = mysql_fetch_array($current_team);
?>
<select name="TeamName">
<option selected value="<?php echo $my_row['TeamID']; ?>"> <?php echo $my_row['TeamName']; ?> </option>
<?php
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
echo "<option value=\"$team_id\">$team_name</option>";
}
echo "</select>";
?>
It seems like simple if condition will solve the case for you:
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
if($team_id != $my_row['TeamID']){
echo "<option value=\"$team_id\">$team_name</option>";
}
}
Additionally you should always sanitize $_GET / $_POST params, in your example:
$player_id = intval($_GET['id']);
Intval will return 0 if the given format is not numeric, so your sql query is safe from this moment.
I am pulling in questions from a questions table in MySQL and populating them in a form. This works fine and I am populating checkboxes as well that the value is populated with the QuestionID. The array is properly populating but I want to take the value of the checked checkboxes (which is my question ID) and insert that ID into a table, so that I have the questions that are selceted for use by their ID. Here is what I have so far:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name=chkQuestion align="left"/><p>' . $row['Question'] .'</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
if (isset($_POST['chkQuestion']))
{
//create the query for the score
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES ($QuestionID)";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Submitted!!</h1>';
}
}//End of IF 'submitted
You want to insert multiple records in one statement is what I'm understanding.
$sql2 = "INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(". implode('),(', $QuestionID) . ")";
This will join each index inside $QuestionID with ),(
If you were to echo $sql2 you would get
INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)
You can use a loop to get the questions that are checked.
for($i=0;$i<count($_POST["chkQuestion"]);$i++) {
"INSERT INTO tbl_QuestionSelected (QuestionID) VALUES('".$_POST["chkQuestion"][$i]."');
}
This way the MySQL statement has the actual values to insert into your table.
try to loop your ids and escape it!!
$ids_list = '';
foreach($_POST["chkQuestion"] as $id)
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
This will assign the value based on the array for the value and insert it into MySQL:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name="QuestionID[' . $row['QuestionID'] . ']">' .$row['Question']. '</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
$ids_list = '';
foreach($_POST["QuestionID"] as $key=>$value) {
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($value);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
}//End of IF 'submitted
}
i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}
Just like the title says i'm having difficulties in achieving it.
Here's my dropdownlist:
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[data] name=\"blabla\">$nt[data]</option>";
}
echo "</select>";
?>
Here's the buttonclick:
<?php
if(isset($_POST['Submit']))
{
$query = "SELECT SUM(suma), paskirtis FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' AND data ='".$_POST['data']."' group by paskirtis";
$result = mysql_query ($query);
echo "<tr><td>Paskirtis:</td><td>Biudzetas:</td><td>Isleista:</td><td>Likutis:</td></tr>";
while($nt=mysql_fetch_array($result)){
if($nt['SUM(suma)'] != null){
$suma = $nt['SUM(suma)'];
}
echo "<tr><td>$nt[paskirtis]</td>
<td><input type=\"text\" name=\"isleista[]\" value=\"Skiriamų pinigų kiekis...\" method=\"post\"></td><td>".$suma." Lt</td><td>--</td></tr> <br>";
}
}
?>
After I press it, it retrieves the data I want from the date I've chosen from the drop down list and also reset whole drop down list showing the first value of the dates from sql database, not the one I selected. If anyone knows how to keep the selected value in the list any help is greatly appriciated!
Try this, you need to place select="selected" in the while loop. See below code how I placed the $selected
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
$selected = ($_POST['blabla'] == $nt[data])?'selected="selected"':NULL;
echo "<option value=$nt[data] name=\"blabla\" $selected >$nt[data]</option>";
}
echo "</select>";
?>