I have a database called school with a table called persons. On my PHP/HTML form I have a selector option with a drop down. I want to pass the value of the drop down into my database.
I thought the below would work, single option is only available. Can anyone see where I am going wrong? DI feel I need to store the value somewhere but Im not sure its even been captured.
index.php
<form action="insert.php" method="post">
<div>
<div>
<div>
<div><label for="Criticality">Criticality</label><select name="critical">
<option value="Critical">Critical</option>
<option value="Important">Important</option>
<option value="Support">Support</option>
<option value="Non Critical">Non Critical</option>
</select></div>
<button type="submit" value="Submit">Submit</button>
</div>
</div>
</div>
</form>
insert.php
<?php
$link = mysqli_connect("127.0.0.1", "root", "password", "school");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$critical = mysqli_real_escape_string($link, $_REQUEST['critical']);
$sql = "INSERT INTO persons (critical) VALUES ('$critical')";
if(mysqli_query($link, $sql)){
header("Location: success.html");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Related
How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.
As the title said, I want to display the specific row of data based on the user selection of the year.
If user selected 2017, I only want to display rows of data that are created in the year of 2017.
I know there are something wrong with my query, I am trying to understand how can I write the query. Can anyone please help me? Thank you in advance!
<form action="Report1.php" method="POST">
Select Year:<select name="sortyear" id="sortyear">
<option>2017</option>
<option>2018</option>
</select>
<?php
$sortyear = $_POST['sortyear'];
$db = mysqli_connect('localhost','root','','customercaremodule');
date_default_timezone_set('Asia/Kuala_Lumpur');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$sql = "SELECT first_name, last_name, email, message, FC_DateTime FROM fbcomplain WHERE (YEAR(FC_DateTime) = $sortyear)";
$result = mysqli_query($db,$sql);
?>
</form>
Ignoring security flaws, you could do the following:
<?php $getYears = sqlquery() ?>
<form action="Report1.php" method="POST">
<select name="sortyear" id="sortyear">
<?php for ($i = 0; $i < $getYears.length; $i++): ?>
<option value="<?php echo $getYears[$i];?>"><?php echo $getYears[$i];?></option>
<?php endif; ?>
</select>
You can do
<?php for () {
}?>
but the for: allows you to drop back to html code and get your syntax highlighting ;)
I managed to solve it by adding a button
<input type ="submit" name="search" class="btn btn-sm btn-primary" value="Filter" style="background-color: #474747;padding: 5px 5px !important;margin-bottom:5px;">
and coded the php this way
if(isset($_POST['search']))
{
$db = mysqli_connect('localhost','root','','customercaremodule');
date_default_timezone_set('Asia/Kuala_Lumpur');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$sortyear = $_POST['sortyear'];
$sql = "SELECT first_name, last_name, email, message, FC_DateTime FROM fbcomplain WHERE (YEAR(FC_DateTime) = $sortyear)";
$result = mysqli_query($db,$sql);
}
You could try this:
<form action="Report1.php" method="POST">
Select Year:<select name="sortyear" id="sortyear">
<option>2017</option>
<option>2018</option>
</select>
<input type="submit" name="submit" value="Get Annual Data" />
<?php
if(isset($_POST['submit'])){
$sortyear = $_POST['sortyear'];
$db = mysqli_connect('localhost','root','','customercaremodule');
date_default_timezone_set('Asia/Kuala_Lumpur');
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$sql = "SELECT first_name, last_name, email, message, FC_DateTime FROM fbcomplain WHERE (YEAR(FC_DateTime) = " .$sortyear .")";
$result = mysqli_query($db,$sql);
}
?>
</form>
Note that this is mostly your code, I just modified it accordingly to this artcile. The key point is I added button, which enables user to submit form.
I have a select dropdown list that contains all existing usernames found in my table. I want to delete an entry from my table by selecting the corresponding username. I can't seem to find the error in my php file...I get the "Successfully deleted" message even if the entry is still there. Want to know what's wrong with my php. Thanks.
Here's the concerned portion of the View:
<form action="deleting.php" method="post">
<select id="username">
<option ng-repeat="user in users">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
Here's my deleting.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "abc";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$deletecontent= isset( $_POST["username"] ) ? $_POST["username"] : "null" ;
$sql = "DELETE from users where username='$deletecontent'";
if (mysqli_query($conn, $sql)) {
echo "Successfully deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
You can get value in $_POST only when there is name attribute in your input. so try
<select id="username" name="username">
You have to add name attribute to select option. Then only it can be accessed using $_POST.
<select id="username" name = "username">
Set name="username" in <select>
and,
set value attribute in <option>.
<form action="deleting.php" method="post">
<select id="username" name="username">
<option ng-repeat="user in users" value="{{user.username}}">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
I'm an high school Italian student, and today my professor assigned me a simple homework:
I have to create a PHP page with a basic form that allows me to introduce a new "student" into a table in MySQL, "name", "surname" and "class".
That's the PHP page:
<html>
<head>
<title> School </title>
</head>
<body>
<?php
$name="";
$surname="";
$conn=mysqli_connect("127.0.0.1","root","");
if(!$conn){ echo 'No connection.'; die;}
if(!mysqli_select_db($conn,"School")) { echo 'Err'; die;}
$result=mysqli_query($conn,"select * from classes");
if(!isset($_REQUEST["submit"])){
echo '<form action="" method="post">
<input type="text" name="name" size="26"> Name <br><br>
<input type="text" name="surname" size="26"> Surname <br><br>
<input type="submit" name="submit" value="Submit">';
if(mysqli_num_rows($result)!=0){
echo '<select name="combobox" id="combobox">
<option value="" selected="selected"> Classes list </option>';
while($combobox=mysqli_fetch_assoc($result)){
$classes=$combobox["classes"];
echo '<option value="'.$combobox["classes"].'">'.$combobox["classes"].'</option>';
}
echo '</select><br><br>';
}
echo '</form>';
}
else{
$name=$_REQUEST["name"];
$surname=$_REQUEST["surname"];
//$query='insert into Students(name,surname,classes) values("'.$name.'","'.$surname.'","'.$classes.'");';
//if(!mysqli_query($conn,$query)) { echo 'Err'; die; }
echo 'Success! <br> Name: '.$name.' <br> Surname: '.$surname.'<br> Class: '.$classes.'<br>';
}
?>
</body>
</html>
I have already created the database with all the tables I need. Now, the thing is, how do I put the "option" that I choose from the <select> into a variable so I can use it for the insert into? Everything I found was just "filling a combobox from mysql".
To get value of select give it name and after get it by it's name with $_GET['name'] or $_POST['name'] if you choose method="post", you will get the selected option value.
html:
<form method="get" action="/script.php">
<select name="name"><option>1</option></select>
<input type="submit" value="send">
</form>
php:
$value=$_GET['name'];
echo $value;
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyDB (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This is what you should follow.
Always give your form elements a name, this is how it gets sent to the backend. With <select>, the value of the selected element will be sent to your code via the name you gave it. Once you do this, you can add a variable for it at the end of your code.
I have a VERY simple form that is not working. What I am trying to accomplish is when the user clicks the update button, they are presented with a form filled in with the information. When they change the information and click update, they are sent back to the main form with all of their changes presented. Everything works but the update. When you change something and click update, nothing is changed. Here is the update form code:
<h4>Update Record</h4>
<?PHP
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
?>
<form action="update_process.php" method="get">
Band: <input type="text" name="artist" value="<?php echo $_GET['artist'] ?>"/><br/>
Album: <input type="text" name="title" value="<?php echo $_GET['title'] ?>" /><br/>
Format: <select name="format">
<option value="Compact Disc" name="compact disc">compact disc</option>
<option value="Album" name="album">album</option>
<option value="Cassette" name="cassette">cassette</option>
<option value="MP3" name="mp3">mp3</option>
</select><br/>
Notes: <TEXTAREA NAME="notes" ROWS="3" COLS="30"><?php echo $_GET['notes'] ?>
</TEXTAREA><br/>
<input type="submit" value="Update" />
</form>
And here is the code for the update_process.php file:
<?php
$artist = $_GET['artist'];
$title = $_GET['title'];
$format = $_GET['format'];
$notes = $_GET['notes'];
//create connection to DB
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "UPDATE music SET title='$title', artist='$artist', format='$format', notes='$notes'
WHERE id='$id'";
if ($con->query($sql) === TRUE) {
header('Location:index.php');
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
In the WHERE clause you says where id = '$id', but where is the $id value set?
I think $id does not have a value.
I see some problems with your code:
1 - where id $id defined?
2 - I guess id is an integer field, so the 's around $id are not needed;
You've mixed object based and function based programming. You started with function based, so I'll show you that way. To query a database, you need to run:
mysqli_query($con,$sql);
Rather than:
$con->query($sql)
There are a few other problems security wise with your code, but skip the rest of my answer if you don't care.
You're not checking to see whether those GET parameters exist before you use them. Use:
if(isset($_GET['artist'],$_GET['track'],...)) {...}
You're also not escaping your query strings, making your site vulnerable to SQL injection. Use:
$artist = mysqli_real_escape_string($con,$_GET['artist']);
Good luck! Just go read the PHP docs, making sure you either take object or function approach for the entire script.