The issue is with doing an INSERT into the dropdown. I was able to populate data from the DB into the drop down. The issue is inserting into a table from the dropdown.
HTML (Generated dropdown from database)
<div class="group">
<label>Subject</label>
<input type="text" name="subject">
</div>
<div class="group">
<label>Group</label>
<select id="ministry" name="group">
<option style="font-family: century gothic">---Select Ministry---</option>
<?php // populate dropdown ?>
<?php foreach($groups as $group): ?>
<option value="<?= $group['group_id'] ?>"><?= $group['groupname'] ?></option>
<?php endforeach; ?>
</select>
</div>
PHP (Code to insert into the database)
<?php
$date = "";
$subject = "";
$group = "";
$message = "";
$sql= "SELECT * FROM groups";
$stmt = $db->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
if (isset($_POST['sendSMS'])) {
$date = (isset($_POST['date']));
$subject = $_POST['subject'];
$group = $_POST['group'];
$message = $_POST['message'];
$sql = "INSERT INTO message (date, subject, group, message)
VALUES
(:date, :subject, :group, :message)";
$stmt->execute(array(
':date' => $_POST['date'],
':subject' => $_POST['subject'],
':group' => $_POST['group'],
':message' => $_POST['message']));
$result = $sql->execute();
echo "SMS sent successfully";
}
?>
I moved your first query to the top of your page. It looks to me that is what is going to populate your html with the group data.
I cleaned up your html a bit. Well formatted code is much easier to read and much easier to troubleshoot when you have issues. I like to avoid breaking in and out of php.
Your insert query is close, but I made a very clear example for you to follow. This should show you the way going forward. Remember: Prepare, Bind, and Execute.
<?php
//DB select statement - This should probably go before your select html
$sql= "SELECT * FROM groups";
$stmt = $db->prepare($sql); //Prepare
//Nothing to bind
$stmt->execute(); //Execute
$groups = $stmt->fetchAll();
echo
'<div class="group">
<label>Subject</label>
<input type="text" name="subject">
</div>
<div class="group">
<label>Group</label>
<select id="ministry" name="group">
<option style="font-family: century gothic">---Select Ministry---</option>';
foreach($groups as $group){
echo
'<option value="' . $group['group_id'] . '">' . $group['groupname'] . '</option>';
}
echo
'</select>
</div>';
if(isset($_POST['sendSMS'])){
//insert into database
$query = "INSERT INTO `message`
(
`date`,
`subject`,
`group`,
`message`
)
VALUES
(
:date,
:subject,
:group,
:message
)";
//Remember these three steps. 1.)Prepare, 2.)Bind, 3.)Execute
$stmt = $db->prepare($query); //Prepare
//Bind
$stmt->bindParam(":date", $_POST['date']);
$stmt->bindParam(":subject", $_POST['subject']);
$stmt->bindParam(":group", $_POST['group']);
$stmt->bindParam(":message", $_POST['message']);
//Execute
$stmt->execute();
echo "SMS sent successfully";
}
?>
Here are two sources for you to read on PDO. I highly recommend looking over both of them and bookmark them so you can reference when you need them.
https://phpdelusions.net/pdo
https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection
<?php
//---session start---
session_start();
//---variables iniatiated and set to empty---
$date = "";
$subject = "";
$group = "";
$message = "";
//--try begins here---
//---include db connection---
require 'db.php';
$sql= "SELECT * FROM groups";
$stmt = $db->prepare($sql);
$stmt->execute();
$groups = $stmt->fetchAll();
if(isset($_POST['sendSMS'])){
//insert into database
$query = "INSERT INTO member(date, subject, group, message) VALUES (:date, :subject, :group, :message)";
$stmt = $db->prepare($query);
$stmt->bindParam(":date", $_POST['date']);
$stmt->bindParam(":subject", $_POST['subject']);
$stmt->bindParam(":group", $_POST['group']);
$stmt->bindParam(":message", $_POST['message']);
$stmt->execute();
echo "SMS sent successfully";
header('location: SMSsent.php');
}
//--close connection---
unset($db);
<form>
<div class="group">
<label>Group</label>
<select id="ministry" name="group">
<?php
foreach($groups as $group){
echo '<option value="' . $group['group_id'] . '">' . $group['groupname'] . '</option>';
}
?>
</select>
</div>
<div class="group">
<label>Message</label>
<textarea
style="text-align: left; vertical-align: middle;"
cols="25" rows="7" name="message" id="clear">
</textarea>
</div>
<button type="submit" class="btn" name="sendSMS">Send SMS</button>
</div>
</form>
Related
How best can I save a select option value name instead of the id using just Ajax, PHP and MYSQL.
I tried many ways but for now when I select the data and store back it keeps saving generated id and that's not what I want.
When i decided to change the id of the selection option to value i the values does show on the drop down.
Details.php
<form method="post" name="signup" onSubmit="return valid();">
<label class="control-label">Profile ID</label>
<select id="employee" name="regcode" class="form-control">
<option value="" selected="selected">Select Profile ID</option>
<?php
$sql = "SELECT id,regcode FROM tbstudentprofile";
$query = $dbh->prepare($sql);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<option name="regcode" value="<?php echo $row["id"]; ?>">
<?php echo $row["regcode"]; ?> </option>
<?php } ?>
</select>
<div class=" form-group1 form-last>
<label class=" control-label">Status</label>
<textarea name="status" row="2"></textarea>
</div>
<button type="submit" name="save">Save </button>
</form>
enter code here
query
if (isset($_POST['save'])) {
$regcode = $_POST['regcode'];
$status = $_POST['status'];
$sql = "INSERT INTO studentschooltbl(regcode,status) VALUES(:regcode,:status)";
$query = $dbh->prepare($sql);
$query->bindParam(':regcode', $regcode, PDO::PARAM_STR);
$query->bindParam(':status', $status, PDO::PARAM_STR);
$query->execute();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$msg = " Registration successfully";
} else {
$error = "error";
}
}
My prepared statements for inserting data into a database are not working. I have had these issues accross the board but I am including one example just incase I am making a simple mistake. The query is running ok as I am getting a message which I placed myself within the code, however nothing is being entered into the actual database. MY issues so far with prepared statements is the lack of feedback you get when something isnt working. Any help would be greatly appreciated.
<?php
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level,
price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject,
$newlevel, $newprice);
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
HTML for form:
<form enctype="multipart/form-data" action='updatesubjects.php' method="post" id="update-subjects-form" name="new-subject" >
<fieldset>
<!--Tutor ID (Posted from previous page) -->
<input type="hidden" name="tutorId" value='<?php echo "$userarray[0]";?>'>
<!-- Subject -->
<div class="form-group">
<label for="subjects">Subject</label>
<select name="subjects" type="text" class="form-control">
<?php
if(mysqli_num_rows($subjectsresult)>0){
while($row = mysqli_fetch_assoc($subjectsresult)){
$get_subjectid = $row['subject_id'];
$get_subjectname = $row['subject'];
echo "<option value='$get_subjectid'>$get_subjectname</option>";
}
}
?>
</select>
</div>
<!-- Level -->
<div class="form-group">
<label for="subjectlevel">Subject Level</label>
<select name="subjectlevel" type="text" class="form-control">
<?php
if(mysqli_num_rows($levelresult) > 0){
while($row = mysqli_fetch_assoc($levelresult)){
$get_levelid = $row['level_id'];
$get_namelevel = $row['level'];
echo "<option value='$get_levelid'>$get_namelevel</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="subjectlevel">Price</label>
<input type='number' step='0.01' min='0' name='price'>
</div>
<button class="btn btn-primary" type="submit" name="newsubject" id="bookingsform">Submit form</button>
</fieldset>
</form>
I apologies for any poor indentation
You need to declare your variables and assign value to them before binding. At the moment you should have undefined variables.
On development environment ensure error reporting is on.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level, price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject, $newlevel, $newprice);
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck
I need to have the array pulling multiple FacultyIDs also connect to the same PubID in the FACULTYPUBLICATION table.
FacultyName is a multiple select option field
Publication is a single insert and creates an auto generated id
the Publication ID gets inserted into the PUBLICATION table
the FacultyID comes from a lookup table that is predefined
the PubID and the FacultyID gets inserted into the FACULTYPUBLICATIONS table
PROBLEM: When multiple Faculty are selected only 1 faculty gets inserted into FACULTYPUBLICATIONS. I need to find a way to connect a single PubID to multiple faculty in the FACULTYPUBLICATIONS table
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyName">Faculty Name</label>
<select multiple="multiple" name="FacultyID" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( '$JournalID', '$Year', '$Comments', '$Volume', '$Issue', '$Title', '$JournalRating' )");
$stmt->execute();
// would need to add inserts for JournalName if we re-add it in
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( '$FacultyMemID', last_insert_id() )");
$stmt->execute();
mysqli_close($conn);
?>
</body>
</html>
To get multiple selections, add [] to the name of the input:
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
This tells PHP to make $_POST['FacultyID'] an array of all the values. Then you can loop through them:
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $conn->insert_id;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('si', $FacultyMemID, $pubID);
for ($_POST['FacultyID'] as $FacultyMemID) {
$stmt->execute();
}
Note that you can't use the SQL LAST_INSERT_ID() in the loop, because after the first iteration it will contain the ID of the row that was just inserted into FACULTYPUBLICATIONS, not the ID of the row that was inserted into PUBLICATION before the loop. So I used the PHP $stmt->insert_id to get the ID.
I've also recoded using bind_param to prevent SQL injection.
This makes it work as well because calling the array from the original function.
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
I have a form that i would like to be processed and sent to my sqlite database. I was trying to store the data in an array which is then sent to the database but i think i need to use an SQL INSERT INTO statement after my submit, i am just unsure on how to implement this properly and if my code is correct so far. I have two different pages:
index.php:
<div id="wrapper">
<div class="banner1">
<h2>Stock Input</h2>
</div>
<form id="form" method="post">
Name:<br>
<input type="text" name="name[0]"/> <br>
Gender:<br>
<input type="text" name="gender[0]"/> <br>
Age:<br>
<input type="number" name="age[0]" min="1" max="99"/> <br>
<input id="submit" type="submit">
</form>
</div>
<div id="results">
<div class="banner2">
<h2>Results</h2>
</div>
<div class="data">
<?php
include 'conn.php';
unset($_POST['submit']);
$data=$_POST;
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
</div>
conn.php
I used an include in my index.php as it was getting messy, not sure if this is proper use but it did the job fine i think. Anyway here is my page that creates or connects to a sqlite database using PDO and prepares and inserts some test data into my array.
<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
$data = array(
array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
);
$insert = "INSERT INTO test (name, gender, age)
VALUES (:name, :gender, :age)";
$stmt = $dbh->prepare($insert);
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->execute();
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
I need the user input data to be submitted from the form to the array and sqlite. Think i'm missing some insert statements, could someone help me and guide me where i'm going wrong.
You have to move the bindParam calls inside the foreach.
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
$stmt->execute();
}
bindParam binds the value of the variable and you have to use it when you when you want to change the value.