Querying Radio buttons into MYSQL database - php

I need advice to use radio buttons in html to query into MYSQL base on the user selection.
The table is called "Trainers"
There are Three trainers:
krillavilla
Novac
Urie
The user choose what trainer he/she want to setup a meeting with. On the MYSQL I want to show the "krillavilla" got "5" meetings with users and "Urie" got "0" meetings with users.
I research this post:
How can i add radio buttons record into MySQL fields using PHP
but I was trying to avoid arrays
And on this post:
Inserting the selection of radio buttons into MySQL
Doesnt answer my question what I am looking for.
This is my php:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","******","******","*****");//This is the login creditial
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());//Error check for execution
}
// Escape user inputs for security
$trainers = mysqli_real_escape_string($link, $_POST['trainers']);
// attempt insert query execution
$sql = "INSERT INTO trainers (trainers) VALUES ('$trainers')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="test2.php" method="post">
<p>
<input type="radio" name="trainers" id="krillavilla">krillavilla
</p>
<p>
<input type="radio" name="trainers" id="Urie">Urie
</p>
<p>
<input type="radio" name="trainers" id="Novac">Novac
</p>
<input type="submit" value="Submit">
</form>
</body>us
</html>
This is my second form page. I am trying to create a GYM schedule using three form webpages where the user will:
Sign up a membership=> User Select the trainer=> User selected what type of membership he/she wants=> confirmation page
but for now i need help of figuring out how can i get my radio buttons data to record how many users that assign to trainer on MYSQL.
BTW I used this:
http://www.tutorialrepublic.com/php-tutorial/php-mysql-insert-query.php
as my guide

you need to set value="Urie" instead of id="Urie"

Related

Taking mySQL database input from HTML form with PHP

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

change from mySQL to SQL and now cant get record creation

I am running WAMP 2.5 on Win7 and created a webpage to insert records into a mySQL database. This worked perfectly.
Then I needed to use SQL Server 2014 (remote server on LAN) instead of mySQL (local in WAMP), and while everything seems ok, i am not getting the records created in the table, yet no error either.
Account used to log in with is db owner.
Any help would be great.
Thanks
Len
Code is as follow (I call sqlconnect.php for db connection) and get confirmation that connection was successful.
File is called insert-data.php so it calls itself if form is empty and Submit is selected.
<?php
if(!empty($_POST['mcpbarcode'])) {
header("Location insert-data.php");
include('sqlconnect.php');
$mcpbarcode = $_POST['mcpbarcode'];
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('$mcpbarcode')";
sqlsrv_query($conn,$sqlinsert);
if (!$sqlinsert) {
die('error inserting new record');
}
$newrecord = "New record added";
}
?>
<html>
<head>
<title> Insert Barcode into Database</title>
</head>
<h3><font color = red>This window must be open and active</font></h3>
<img src="header.jpg" alt="anyname" style="width:800px;height:165px;">
<body>
<h1> Insert barcode into Database</h1>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<label>Barcode:<input type="text" name="mcpbarcode" autofocus /></label>
<br /><br />
<input type="submit" value="Add new record" />
</form>
<?php
$newrecord="";
echo $newrecord
?>
</body>
</html>
See if it's working like that:
If mcpbarcode column is a string type (varchar, char etc):
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('".$mcpbarcode."')"
OR if mcpbarcode column is int, float, etc:
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES (".$mcpbarcode.")"
but you should have an error on mysql also ...

How to prevent a php script form changing to another page

I used a sample I found here with a HTML page calling a PHP script, both are listed below.
It all works well - BUT, I end up with the PHP scrip page and I want to avoid it - I want to stay on the HTML page and NOT move anywhere. I read in some places that I will need JS or AJAX but can't see any actual example.
I am working on my PC under Windows 7 with IIS version 7.5 installed, PHP 5.3.28.
and executing the HTML file inside c:\inetpub.wwwroot
HTML
<div id="contact">
<h2>Enter your First and Last Name</h2>
<form action="frm_script.php" method="post" target="_parent">
<p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
<p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</div>
PHP Script
<?php
if(isset($_POST['submit']))
{
//get the name and comment entered by user
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//connect to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to
MySQL server');
$check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and
lastname='$lastname'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0)
{
print "customer exists";
}
else
{
//insert results from the form input
$query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
$result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
mysqli_close($dbc);
}
print '<script type="text/javascript">';
print 'alert("The Customer is NOW registered")';
print '</script>';
};
?>
A html document containing a form with an action="" statement results to change to the assigned page. Like yours, to frm_script.php
If you don´t want this to occure, you need an AJAX-request, as you mentioned above, or you can add a
header(location: 'FPRM.HTML');
to the bottom of the php script. So after processing, which should be very fast, the original page is loaded again.
Or you don´t use two pages at all. Just put the html code from FPRM.HTML to the bottom, after the php code, so the page just will be reloaded once the form values are saved. In this case, call the concatenated document simply FPRM.php, and the form action must be set to action="FPRM.php" or is simply not needed, as the form without action statement loads the same page anyway.

Element inside div not submitting

Why this code doesn't work? I have
<script>
//script to retrieve a list from a page and place it inside a div.
</script>
//This is the list on the otherpage.
<select name='timing' id='timing'> Some Options </select>
The div in which it is placed
<html>
<body>
<form method="post" action="insert.php">
<div id="time"></div>
//some more elements and a submit button
</form>
</body>
</html>
On submit the data should go to a php page which inserts data into the databas
<?php
session_start(); //Use this to include session variables
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO appointment(username, doctor, day, time) VALUES('$_SESSION[username]', '$_POST[doctor]', '$_POST[day]', '$_POST[timing]')";
// So on.
The problem is the form submits all the values except the one placed inside the div
Any ideas? I've been stuck on this for a long time.
the form dont submit div .
the form submit inputs value
change your div to an input
<input type="time" name="time" />
this is HTML5 Time Input
some referense for time input types

Insert row into MQSQL Database only under certain conditions

Before reading, please note that I am very new to both PHP and MYSQL. I have created a table in my MYSQL database. I would now like to 'spit out' this table onto a page through PHP. This part I seem to be okay with. After outputting the tables data into an HTML table, I would like to output an HTML form onto my page. So, I now have a table followed by a form. This form will contain a few text boxes that, when submitted, will post the data used to insert a new row into the preexisting table noted above.
All of the above code is currently in a PHP file named 'display.php'.
My Issue:
If the form described above is posting back to my 'display.php' file, after inserting a new row and displaying the new table information, what is stopping my code from inserting another new row full of NULL data? I'm sure I did a less than decent job of explaining this scenario so I will post some code.
HTML / PHP
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="insertdata.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
<?php
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
// Insert posted data into table
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
('$_POST[username]','$_POST[hardwareid]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
?>
</body>
</html>
Again, I am a complete beginner - and I understand this. I want to know, must the different parts of the above code be placed into multiple files? I don't want to have to go to a new address, which is why this is causing me so much confusion I'd say.
try some thing like this,
connection.php file
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
display.php file
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="process.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
</body>
</html>
process.php file
include_once("ur_file_dir/connection.php");
if ((isset($_POST['username']) && isset($_POST['hardwareid'])) {
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
($_POST['username'],$_POST['hardwareid'])";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
}
You should validate your input, ie:
if (!empty($_POST['username'] && !empty($_POST['hardwareid']) {
// do your insert here
}
Also, you should be wary of allowing user input to be inserted directly into your query, as this leaves your open to SQL injections. A better way to do this is to use PDO and prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php

Categories