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.
Related
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>
I'm totally stuck on a problem. I'm practicing MySQL data inserts from php, but I am unable to get it working. I am totally new when it comes to php. With MySQL and HTML, I did a few courses on it, so you can say I'm a beginner. This is part three of the example, the first example you have to list all the animals in the table, that part I got working, then the second part is where I have to use a named parameters to extract specific animal types, and it also works fine. Now I'm stuck with the last one inserting data. I have a simple form with animal name and animal type as text boxes, when I click on submit the updated row must auto update in example one and show in the table, but when I click on submit, nothing happens, nothing is inserted into the database, but when I refresh the page or click submit again, then only do I see the updated data. And when fill in data in the two text fields after I clicked refresh or submit, blank data is inserted into the database.
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST[animal_type];
$animal_name = $_POST[animal_name];
$query = "INSERT INTO animals
(animal_type, animal_name)
VALUES
('$animal_type', '$animal_name')";
$animal = $db->prepare($query);
$animal->bindValue(':animal_id', $animal_id);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
Any help would be greatly appreciated.
JasonK
Update
So this is what it looks like when completed, but you see those blank entries is what happens when I fill in animal type and animal name and click submit - it just leaves the fields blank, I checked in the database, it does the insert when I click submit. I deduced that whenever I click submit or do a page refresh, it runs the whole code again that is where the blank entries comes from.
This is what my whole code look like.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
/////////////////////////////////////////////////////////////////////////////////Example1/////////////////////////////////////////////////////////////////////////////////////////
<?php include 'menu.inc';
$db = 'mysql:host=localhost;dbname=animal';
$username = 'jason';
$password = '';
try {
$db = new PDO($db, $username, $password);
echo 'Connection successful';
echo '<br />';
}
catch(PDOException $e)
{
echo 'Connection failed' . $e->getMessage();
}
$query = 'SELECT animal_type, animal_name
FROM animals';
$animal = $db->query($query);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
echo "<br>";
?>
<table border="1">
<tr>
<th>Animal Type</th>
<th>Animal Name</th>
</tr>
<?php foreach ($animals as $animal) { ?>
<tr>
<td><?php echo $animal['animal_type']; ?></td>
<td><?php echo $animal['animal_name']; ?></td>
</tr>
<?php } ?>
</table>
/////////////////////////////////////////////////////////////////////////////////Example2/////////////////////////////////////////////////////////////////////////////////////////
<?php
$animal_type = "leopard";
$query = 'SELECT *
FROM animals
WHERE animal_type = :animal_type';
$animal = $db->prepare($query);
$animal->bindValue(':animal_type', $animal_type);
$animal->execute();
$animals = $animal->fetchAll();
$animal->closeCursor();
?>
<p>
<table border="1">
<tr>
<th>Animal Type</th>
<th>Animal Name</th>
</tr>
<?php foreach ($animals as $animal) { ?>
<tr>
<td><?php echo $animal['animal_type']; ?></td>
<td><?php echo $animal['animal_name']; ?></td>
</tr>
<?php }?>
</table>
</p>
/////////////////////////////////////////////////////////////////////////////////Example3/////////////////////////////////////////////////////////////////////////////////////////
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'jason';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$db = new PDO('mysql:host=localhost;dbname=animals', $username, $password);
$query = "INSERT INTO animals
SET animal_type = :animal_type,
animal_name = :animal_name";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type, PDO::PARAM_STR);
$animal->bindParam(':animal_name', $animal_name, PDO::PARAM_STR);
$animal->execute();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
</body>
</html>
To get value from super_globals like ($_POST,$_REQUEST,$_GET) you have to pass index as string
change
$animal_type = $_POST[animal_type];
$animal_name = $_POST[animal_name];
to
$animal_type = $_POST["animal_type"];
$animal_name = $_POST["animal_name"];
And remove un-necessary binding value
$animal->bindValue(':animal_id', $animal_id); //remove this
Also hope you have created database connection and store it in $db
Your insert query is also vulnerable to SQL Injections. Use bind param to insert value
$query = "INSERT INTO animals
(animal_type, animal_name)
VALUES
(:animal_type, :animal_name)";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type);
$animal->bindParam(':animal_name', $animal_name);
$animal->execute();
<?php
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$db = new PDO('mysql:host=localhost;dbname=animals', $username, "");
$query = "INSERT INTO animals
SET animal_type = :animal_type,
animal_name = :animal_name";
$animal = $db->prepare($query);
$animal->bindParam(':animal_type', $animal_type, PDO::PARAM_STR);
$animal->bindParam(':animal_name', $animal_name, PDO::PARAM_STR);
$animal->execute();
?>
<form action="example3.php" method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" />
</form>
where do you create the database? the only thing i see is a string named $db I think you forgot to create a PDO object like this
$db = new PDO('mysql:host=localhost;dbname=animals', $username, "");
otherwise ist try's to a prepare statement to a string
and array indexes must be a string like this $_POST["animal_type"]
<?php
if(isset($_POST['submit'])){ //check wheter form submit or not
$db = 'mysql:host=localhost;dbname=animals';
$username = 'root';
$password = '';
$animal_type = $_POST['animal_type'];
$animal_name = $_POST['animal_name'];
$stmt = $db->prepare("INSERT INTO animals
(animal_type, animal_name) VALUES (?, ?)");
$stmt->bind_param("ss", $animal_type, $animal_name);
$stmt->execute();
}
?>
<form method="post">
Animal Name: <input type="text" name="animal_name"><br>
Animal Type: <input type="text" name="animal_type"><br>
<input type="submit" name="submit"/> // change this markup input
</form>
Refer this link for more php and mysql tutoral https://www.w3schools.com/PhP/php_mysql_prepared_statements.asp
My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}
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 got a nuevo.php that means 'new client' to insert in a mysql database.
I have a lot of input text to register data into mysql, like this :
<label for="Nombre">Nombre : </label><br/>
<input width="50" type="text" class="form-control" id="Nombre" name="Nombre" placeholder="Introduce nombre">
... all inside this ...
<form action="" method="POST" role="form">
And a button like this :
<button type='submit' value='Modificar' class='btn btn-primary'>Registrar</button>
And in index.php, I got this code to register data into mysql finally ...
$app->post('/nuevo', function() use($app, $db){
$request = $app->request;
$nombre = $request->post('Nombre');
$apellidos = $request->post('Apellidos');
$nifcode = $request->post('NIF');
$direccion = $request->post('Direccion');
$email = $request->post('Email');
$telefono = $request->post('Telefono');
$estado = $request->post('Estado');
$provincia = $request->post('Provincia');
$numProvincia = $request->post('numProvincia');
$dbquery = $db->prepare("INSERT INTO Clientes(Nombre, Apellidos, NIF, Direccion, Email, Telefono, Estado, Provincia, numProvincia)
VALUES (:nombre, :apellidos, :NIF, :direccion, :email, :telefono, :estado, :Provincia, :numProvincia)");
$res = $dbquery -> execute(array(
':nombre' => $nombre,
':apellidos' => $apellidos,
':NIF' => $nifcode,
':direccion' => $direccion,
':email' => $email,
':telefono' => $telefono,
':estado' => $estado,
':Provincia' => $provincia,
':numProvincia' => $numProv));
It register all well, all EXCEPT Provincia.
For this, in nuevo.php I'm using another thing that isn't an input text : SELECT OPTION
<form method="get">
<?php
$host="localhost";
$link=mysql_connect($host, "USER", "PASS");
$db=mysql_select_db("pvenecia", $link);
$cdquery="SELECT DISTINCT Provincia, numProvincia FROM Clientes ORDER BY Provincia";
$cdresult=mysql_query($cdquery);
?>
<select id="Provincia" name="Provincia" style="width: 300px" onchange="javascript:cambiarProvinciaSeleccionada();">
<?php
while($row=mysql_fetch_array($cdresult)) {
$defect = "";
if ($row['Provincia'] == 'SIN INFO. PROVINCIA') {
$defect = " SELECTED ";
}
echo "<option value='".$row['numProvincia']."' ".$defect.">".htmlentities($row['Provincia'])."</option>";
echo "<br/>";
};
mysql_close($link);
?>
</select>
</form>
I NEED TO KNOW HOW TO GET THE VALUE FROM SELECT OPTION SELECTED, FOR WHEN I SUBMIT, POST INTO INDEX.PHO AND REGISTER THIS VALUE CORRECTLY. Thanks.
For retrieving the value it does not make any difference between text message or select / drop-down.
value can be retrieved using GET/POST method by name. Ex:
$provincia = $request->post('Provincia');
I think because your form in nuevo.php is in method="GET" try to change it in method="POST" and use
$request->post('Provincia')