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')
Related
I'm working on a CRUD system and currently, I am in the Update section. I have old values from users that need to be updated to new ones through an HTML form.
Right now I am trying to retrieve the POST values from the HTML form set to the post method. After that, I update the user info with the new values gained from the POST request.
<?php
$oldId = $_GET['id'];
$conn = mysqli_connect('localhost', 'root', '')
or die('Verbinding met database server is mislukt.');
mysqli_select_db($conn, 'crudopdracht')
or die('De database is niet beschikbaar');
$query = "SELECT * FROM gebruikers WHERE id = $oldId";
$result = mysqli_query($conn, $query)
or die (mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$naam = $row['naam'];
$leeftijd = $row['leeftijd'];
$gender = $row['gender'];
$locatie = $row['locatie'];
};
?>
<form action="" method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id" <?php echo 'placeholder="' . $oldId . '"><br>';?>
<label for="naam">Naam:</label><br>
<input type="text" id="naam" name="naam" <?php echo 'placeholder="' . $naam . '"><br>';?>
<label for="leeftijd">Leeftijd:</label><br>
<input type="text" id="leeftijd" name = "leeftijd" <?php echo 'placeholder="' . $leeftijd . '"><br>';?>
<label for="gender">Geslacht:</label><br>
<input type="text" id="gender" name="gender" <?php echo '[placeholder="' . $gender . '"><br>';?>
<label for="locatie">Locatie:</label><br>
<input type="text" id="locatie" name = "locatie" <?php echo 'placeholder="' . $locatie . '"><br><br>';?>
<input type="submit" value="Verstuur" id="submit" name="submit">
</form>
</div>
<?php
if(isset($_POST["submit"])){
echo 'hello';
$id = $_POST["id"];
$naam = $_POST["naam"];
$leeftijd = $_POST["leeftijd"];
$gender = $_POST["gender"];
$locatie = $_POST["locatie"];
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
mysqli_query($conn,$query2);
}
?>
In my opinion, I expect the values to change to the new ones set in the HTML form, but they always return the old values.
SQL injection issues aside (as you've stated it isn't in scope of the particular issue), you need to correctly format your SQL query for any non-integer values, so that they are encapsulated with quotes ('[value]').
Your query would current run as:
UPDATE gebruikers ( id = somevalue, naam = somevalue, leeftijd = somevalue, gender = somevalue, locatie = somevalue WHERE id = 12345`
In this query, SQL would attempt to interpret your values as entities (columns, tables), which is obviously not what you want.
So, although you should never inject user input values into a query, the following should fix your issue:
Change
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
to
$query2 = "UPDATE gebruikers SET id = $id, naam = '$naam', leeftijd = '$leeftijd', gender = '$gender', locatie = '$locatie' WHERE id = $oldId";`
Assuming id is an INT field, and the others are strings.
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'm a complete newbie in php & MySQL
Basically what I want to do is be able to retrieve data from a table
in MySQL database and put it in a drop down menu .
After I fill in the other fields I want to data from the drop down menu to be written to another table in the same database .
This is my insert.php file
<?php
#### INSERTS A SINGLE CUSTOMER IN Company-->Customer Database with UTF8 Change for special German Characters - Cyrilic Doesnt work - Other change then utf8 ???
#### Getting Data from Index.php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "company";
//making an array with the data recieved, to use as named placeholders for INSERT by PDO.
#### Getting DAta from Index.php
$data = array('CustomerName' => $_POST['CustomerName'] , 'Address1' => $_POST['Address1'], 'Address2' => $_POST['Address2'], 'City' => $_POST['City'], 'PostCode' => $_POST['PostCode'], 'CountryID' => $_POST['CountryID'], 'ContactName' => $_POST['ContactName'], 'ContactEmail' => $_POST['ContactEmail'], 'ContactPhone' => $_POST['ContactPhone'], 'ContactFax' => $_POST['ContactFax'], 'Website' => $_POST['Website']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); ### Database Connect with Special characters Change
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query with named placeholders to avoid sql injections
$query = "INSERT INTO customer (CustomerName, Address1, Address2, City, PostCode, CountryID, ContactName, ContactEmail, ContactPhone, ContactFax, Website )
VALUES (:CustomerName, :Address1, :Address2, :City, :PostCode, :CountryID, :ContactName, :ContactEmail, :ContactPhone, :ContactFax, :Website )";
//statement handle $sth
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>
And this is the source from the html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Product</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="CustomerName">CustomerName:</label>
<input type="text" name="CustomerName" id="CustomerName">
</p>
<p>
<label for="Address1">Address 1:</label>
<input type="text" name="Address1" id="Address1">
</p>
<p>
<label for="Address2">Address 2:</label>
<input type="text" name="Address2" id="Address2">
</p>
<p>
<label for="City">City:</label>
<input type="text" name="City" id="City">
</p>
<p>
<label for="PostCode">Post Code:</label>
<input type="text" name="PostCode" id="PostCode">
</p>
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
<p>
<label for="ContactName">Contact Name:</label>
<input type="text" name="ContactName" id="ContactName">
</p>
<p>
<label for="ContactEmail">Contact Email:</label>
<input type="text" name="ContactEmail" id="ContactEmail">
</p>
<p>
<label for="ContactPhone">Contact Phone:</label>
<input type="text" name="ContactPhone" id="ContactPhone">
</p>
<p>
<label for="ContactFax">Contact Fax:</label>
<input type="text" name="ContactFax" id="ContactFax">
</p>
<p>
<label for="Website">Website:</label>
<input type="text" name="Website" id="Website">
</p>
<input type="submit" value="Add Records">
</form>
</body>
</html>
So I wanna add this php code that pulls out the country list and prefixes for the phone numbers and then when I hit the submit button the actual output of the drop down menu to we written in the customers table
<p>
<label for="CountryID">Country:</label>
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "company";
$con_qnt = mysqli_connect($servername, $username, $password, $dbname);
if(!mysqli_connect("localhost","root",""))
{
die('oops connection problem ! --> '.mysqli_connect_error());
}
if(!mysqli_select_db($con_qnt, "company"))
{
die('oops database selection problem ! --> '.mysqli_connect_error());
}
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
I don't even know if this is doable - I searched for long time but couldn't find anything that is kind of what I need . Mostly I found hard coded html dropdown menus . In fact hard coding this will work for the countries but it wont work if I want it to be able to show lets say products in a drop down menu . Thank you all in advance .
Hi I just made a quick sample to answer your question on how to populate dropdown using data from database.
In this example, I used
JQuery's AJAX Function
so first, for the backend, (this is just a quick sample to select data. Do not use this as a pattern for your future codes
<?php
$dbh = new PDO("mysql:host=localhost;dbname=dbhelp", 'root', 'pup');
$stmt = $dbh->prepare("SELECT * from t_country");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
?>
I repeat. This is just for quick reference. Do not use it as a pattern for your code.
So using that code, we have now selected data from our table country and usedjson_encode to make it in json format. read more about this here. http://php.net/manual/en/function.json-encode.php.
Next one is the frontend(HTML part)
<body>
// empty dropdown button to be filled by data from database
<select id="country">
</select>
//include the jquery library
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax ({
url : 'dropdown_database.php', // the url from which the data will be pulled
success: function(data) {
var country = $.parseJSON(data); // parse the json format data
$.each(country, function(i, d) {
$('#country').prepend('<option>'+ d.country +'</option>'); // this one adds the <option></option> tag in the dropdown
});
}
});
});
</script>
If I got you right, you want to replace this:
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
With a dropdown so you can quickly pick the country from the dropdown instead of memorizing the ID for each individual country. And to create the select you are using this code:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
That should work fine... after you fix some issues:
If you want to replace the input with the select, the select should have the same name as the input so the value is processed automatically. Right now the select has "label" as the name and there is a strange (and incorrect) name tag. To fix this:
Get rid of the unnecessary name tag.
Replace the name attribute in the select with value "CountryID":
echo "<select name='CountryID'>";
The option value should be the country ID so, unless the ID is the country name (not the best choice), you are not using the right value. Change that line too:
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
(Considering CountryID as the ID, replace it for the right column name).
And I think with those two changes, the rest of the code should work just fine with insert.php that wouldn't require any updates at all. Finally it would look something like this:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='CountryID'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
</p>
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.