Saving a value from select option to database - php

So i am trying to insert some data in my database, unfortunatly it doesn't work as i hoped.
This is my index.php file here i made a little piece of php code to get the select options from my database(this works fine). But now i want people to select from the options in my database and store the selected option in another db table.
<?php
$query = "SELECT event_naam FROM events";
$result2 = mysqli_query($dbconn, $query);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[0]</option>";
}
?>
<form class="inschrijven" method="POST" action="includes/inscscript.php">
<select name="iselect">
<?php echo $options;?>
</select><br><br>
<span>Uw Naam: </span><input type="text" name="inaam" placeholder="Naam"><br>
<span>Leeftijd: </span><input type="number" name="leeftijd"><br>
<span>Aantal Personen:</span><input type="number" name="personen"><br>
<input type="submit" name="inschrijven" value="Inschrijven!">
</form>
I have tried this, but it doesn't do anything it also doesn't give an error.
require_once 'connectie.php'; //Connection to Database File
$sql = "INSERT INTO inschrijven (inschrijf_event, inschrijf_naam, inschrijf_leeftijd, inschrijf_personen) VALUES
('".$_POST['iselect']."','".$_POST['inaam']."','".$_POST['leeftijd']."','".$_POST['personen']."')";
if ($dbconn->query($sql) === TRUE) {
header( "Location: ../index.php" );
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $dbconn->error."');</script>";
}
$dbconn->close();
This is my inscscript.php file
I tried searching for similair qeustions but couldn't find anything like this.

$query = "SELECT event_naam FROM events";
$result=mysqli_query($con,$query)
{
// Return the number of rows in result set
while($rowcount=mysqli_num_rows($result)){
echo "<option value='".$rowcount['event_naam']."'>".$rowcount['event_naam']."</option>
}
Include this php file to your html between select opend and closing tags

Related

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

PHP fetch value from database and display it in the inside the HTML

I have a system where I have a problem I have this code where I just follow inside a youtube video. but change some text. here is my code
<label>Department</label>
<select>
<?php
include 'php/connect.php';
$sql = "SELECT member_type_id FROM member_type";
$result = mysqli_query($conn, $sql);
echo "Select a Department";
while ($row =mysql_fetch_array($result)) {
echo "<option value='" . $row['member_type_id'] ."'>" . $row['member_type_id'] ."</option>";
}
?>
</select>
The problem is, It doesn't show me the value inside that table, here is my database table
the html file is OK, but when I click subit, I always get member registration failed someone correct my code please
<?php
include 'php/connect.php';
$Lname = $_POST['Lname'];
$Fname = $_POST['Fname'];
$Mname = $_POST['Mname'];
$Bdate = $_POST['Bdate'];
$Address = $_POST['Address'];
$Contact = $_POST['Contact'];
$member_type_id = $_POST['Dept'];
$Gender = $_POST['Gender'];
if($Lname == '' OR $Fname == '' OR $Mname =='' OR $Bdate == '' OR $Address =='' OR $Contact =='' OR $Gender =='' OR $member_type_id =='')
{
echo "Fill in all the forms";
}
else {
$sql = "INSERT INTO members (Lname, Fname, Mname, Bdate, Dept, Address, Contact, Gender)
VALUES ('$Lname', '$Fname', '$Mname', '$Bdate',
'$member_type_id', '$Address', '$Contact', '$Gender')";
if ($conn->query($sql) === TRUE)
{
echo "A Member has been added successfully";</script>";
}
else
{
echo "Member Registration Failed";
}
}
$conn->close();
?>
Well to start your HTML is invalid, specifically:
echo "Select a Department";
This will result in HTML something like this
<select>
Select a Department
<option value="1">Faculty</option>
...
</select>
Instead echo the first thing as an actual option
echo '<option value="" >Select a Department</option>'
So your HTML will be proper
As far as the Query goes, who knows. Without knowing if you set $conn and have a proper connection.
$result = mysqli_query($conn, $sql);
Besides that
$sql = "SELECT member_type_id FROM member_type";
Only gives you the number (no one want to select 1, 2 or 3) how will they know 1=Faculty?
$sql = "SELECT * FROM member_type";
Will give you everything, like in PHPmyAdmin. And then:
echo "<option value='" . $row['member_type_id'] ."'>" . $row['member_type'] ."</option>";
Will give you the text, assuming your $conn variable is a proper connection resource.
Lastly this quoting stuff, is ugly. Instead do this ( I cant stand single quotes in HTML)
echo '<option value="'.$row['member_type_id'].'">'.$row['member_type'].'</option>';
That said if you must use singe quotes, at least use variable interpolation in a sensible way.
echo "<option value='{$row['member_type_id']}'>{$row['member_type']}</option>";
One other thing (the thing)
mysql_fetch_array
The mysql_* set of functions are dead as of PHP7 and there is a huge diffrence between mysql_ and mysqli_. But on top of that you want mysqli_fetch_assoc() as in:
while ($row =mysqli_fetch_assoc($result)) {
UPDATE
Probably the most important thing is turn on display errors and error reporting. Let PHP tell you what is wrong, why struggle with it.
<?php
error_reporting(-1);
ini_set('display_errors','1');
Saying It's not working or posting a huge block of code in a comment, is not helpful. Programing is hard. It's like math, you have to be exact in what you do or it won't do what you expect. There are many hundreds of things that can go wrong and typically only a handful of things that will work.
Thanks!
Update your connection string
<label>Department</label>
<select name='memberName'>
<option>Select</option>
<?php
// Create connection
$conn = mysqli_connect("localhost", "root", "", "library_system");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT member_type_id FROM member_type";
$result = mysqli_query($conn, $sql);
echo "<select member_type_id='sub1'>";
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['member_type_id'] ."'>" . $row['member_type_id'] ."</option>";
}
?>
</select>
Use the code below, and you will get the desired results-
<label>Department</label>
<select>
<option value="">Select a Department</option>
<?php
include 'php/connect.php';
$sql = "SELECT member_type_id, member_type FROM member_type";
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_array($result)) {
echo "<option value='" . $row['member_type_id'] ."'>" . $row['member_type'] ."</option>";
}
?>
</select>
try this.
<?php
include 'php/connect.php';
$sql = "SELECT member_type_id FROM member_type";
$option = '';
while($row = mysql_fetch_assoc($sql))
{
$option .= '<option value = "'.$row['member_type_id'].'">'.$row['member_type_id'].'</option>';
}
?>
<html>
<body>
<form>
<select>
<?php echo $option; ?>
</select>
</form>
</body>
</html>

mySQL php update

How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}
How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");
You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.

PHP multi option search query ....?

I'm trying with search box, I created a form as below:
<form method="post" action="search.php">
<select name="purpose">
<option value="" selected="selected">-any-</option>
<option value="For Sale">For Sale</option>
<option value="For Rent">For Rent</option>
</select>
<select name="type">
<option value="" selected="selected">-any-</option>
<option value="Bungalow">Bungalow</option>
<option value="Apartment">Apartment</option>
</select>
<select name="location">
<option value="" selected="selected">-any-</option>
<option value="Norway">Norway</option>
<option value="Itley">Itley</option>
</select>
<input type="submit" value="Search">
</form>
Search.php
I'm trying with these queries but getting problem:
$purpose=$_POST['purpose'];
$type=$_POST['type'];
$location=$_POST['location'];
If I put AND query like this:
SELECT * FROM test WHERE purpose='$purpose' AND location='$location' AND type='$type'
then it not filter one by one result its appear blank.
If I put OR query like this:
SELECT * FROM test WHERE purpose='$purpose' OR location='$location' OR type='$type'
Then it filter mix results.
I want if all selected it filter (purpose >> type >> location) AND if one selected then filter by this but exact result else show
Result not found!
EDIT Adding update made in comments:
I'm doing like this but it showing error:
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
while ($row = mysql_fetch_array($sql))
echo $row['purpose'];
echo $row['location'];
echo $row['type'];
I want if not match display result not found else it filter by all and one by one.
Put that after obtaining the variables:
$sql = array();
if (!empty($purpose)) {
$sql[] = "purpose='$purpose'";
}
if (!empty($type)) {
$sql[] = "type='$type'";
}
if (!empty($location)) {
$sql[] = "location='$location'";
}
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM test" . (!empty($sql)?: " WHERE " . $sql: '');
EDIT: After seeing your comments
First, you should make the connection to the database with the mysql_connect functions. Let's say, for example, that you have this piece of code:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
In the $link var now you have your mysql handle. This piece of code must go at the first of every page where you wanna use the mysql connection. Once you have the SQL sentence (in the code I first wrote, the $sql var), use this after:
$result = mysql_query($sql);
if (mysql_num_rows($result) === 0) {
echo 'Result not found';
}
while ($row = mysql_fetch_array($result)) {
echo $row['purpose'] . '<br/>';
echo $row['location'] . '<br/>';
echo $row['type'];
}
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";

What is wrong with my SQL Insert code?

I'm struggling with trying to find out why this code isn't working for me. I have tables: albums (albumid, albumname), composers (composerid, composername) and tracks (trackid, tracktitle, albumid, composerid).
When I use my form to add a track and link it to a composer and an album from this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20"></textarea></p>
<p>Composer: <select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['composerid'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";} ?>
</select></p>
<p>Place in albums:<br />
<?php while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['albumid'];
$aname = htmlspecialchars($alb['albumname']);
echo "<label><input type='checkbox' name='albs[]'
value='$aid' />$aname</label><br />\n";
} ?>
</p>
<input type="submit" value="SUBMIT" />
</form>
<?php endif; ?>
I get this message:
New track added
Error inserting track into album 2:
Track was added to 0 albums.
The php code that precedes the form is:
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$tracktitle = mysql_real_escape_string($tracktitle);
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click
"Back" and try again.');}
$sql = "INSERT INTO tracks (tracktitle)
VALUES ('$tracktitle')" ;
if (#mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>
echo mysql_error() ');}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO tracks (trackid, albumid,
composerid) VALUES " .
"($trackid, $albs, $cid)";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>'; }}?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<?php
else: // Allow the user to enter a new track
$composers = #mysql_query('SELECT composerid, composername
FROM composers');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = #mysql_query('SELECT albumid, albumname FROM albums');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');}?>
I keep searching for why this is failing and I keep hitting brick walls. I also know that at present it's not very secure which will be the next thing I sort out. I just want to get the actual function working first.
#paj: Change
if ($ok) {
to
if (mysql_query($sql)) {
-
I also suggest you update your SQL statements to
$sql = "INSERT INTO tracks (tracktitle) VALUES ('" . $tracktitle . "')";
$sql = "INSERT IGNORE INTO tracks (trackid, albumid, composerid) VALUES (" . $trackid . ", " . $albID . ", " . $cid . ")";
Looks to me like $ok doesn't exist except in the if ($ok) {
line. It needs to be defined somewhere prior, otherwise it will always read false because it doesn't exist.
Actually you can skip the $ok which doesn't exist and put in if (#mysql_query($sql)) { for that line like you have above. I do have to agree with the comments that the code needs some love, but if you want to know why it's breaking down, it appears this is why.

Categories