php and mysql form connection and inserting error - php

I'm creating a form to save the 'id' and the 'eventname' to save in the database. i'm trying to save the form data into the table but not able to..here's the database code and the form code. please help. i tried but not able to try out the problem. I'm not getting any error but the data's what i enter in the form is not getting saved into the database..
//table structure
CREATE TABLE `event` (
`Memberid` int(7) NOT NULL,
`events` varchar(50) COLLATE latin1_general_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
//form code
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?php
if(isset($_POST['add']))
{
// database connection
$host_name = 'localhost';
$host_user = 'root';
$host_pass = '';
$conn = mysql_connect($host_name, $host_user, $host_pass);
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
//code for SQL injection
if(! get_magic_quotes_gpc() ) {
$login = addslashes ($_POST['login']);
$eventList = addslashes ($_POST['eventList']);
} else {
$login = $_POST['login'];
$eventList = $_POST['eventList'];
}
//inserting data into the database table
$sql = "INSERT INTO EVENT " . "(login, eventList) " . "VALUES " .('$login','$eventList')";
mysql_select_db('database');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
} else
{
?>
<div class="container">
<!-- Codrops top bar -->
<section class="main">
<form class="form-3" method="POST" action="<?php $_PHP_SELF ?>">
<p class="clearfix">
<label for="login">Username</label>
<input type="text" name="login" id="login" placeholder="Username">
</p>
<p class = "clearfix">
<label for="select">Event Name</label>
<select style="width:200px;" name="eventList" tabindex="5">
<option value="select">Select Event</option>
<optgroup label="Do Re Me">
<option value="Battle of Bands">Battle of Bands</option>
<option value="Eastern">Eastern</option>
<option value="Solo">Solo</option>
</optgroup>
</select> <br>
</p>
<p class="clearfix">
<input type="submit" name="submit" value="Sign in">
</p>
</form>
</section>
</div>
<?php
}
?>
</body>
</html>

Related

Insert And Retrieve Data in MySQL with $.post Noob Question

Trying to insert data into MySQL database with PHP. I don't want to refresh the page. The data isn't inserted when I press the Send Message button, but the data is displayed. Please help a noob out. Here's the HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
<form method="POST" action="form.php" id="foo" name="foo">
<h1>Contact Form</h1>
<table>
<tr>
<td>
<label for="fname">Full Name:</label><br>
<input type="text" name="fname" placeholder="John Doe" id="">
</td>
</tr>
<tr>
<td>
<label for="email">Your Email:</label><br>
<input type="email" name="email" placeholder="example#gmail.com" id="">
</td>
</tr>
<tr>
<td>
<label for="msg">Your Message:</label><br>
<textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Send Message">
</td>
</tr>
</table>
</form>
</div>
<p id="target">
</p>
<script>
$(function() {
$("#foo").submit(function(event){
// Stop form from submitting normally
event.preventDefault();
/* Serialize the submitted form control values to be sent to the web server with the request */
var formValues = $(this).serialize();
// Send the form data using post
$.post("form.php", formValues, function(response){
$('#target').load('show.php');
});
});
});
</script>
</body>
</html>
Here's form.php which is supposed to insert data into the database:
<?php
error_reporting(E_ALL);
log_errors(1);
display_errors(1);
if(isset($_POST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$message = $_POST['msg'];
//database details. You have created these details in the third step. Use your own.
$host = "localhost";
$username = "user";
$password = "GoTn_1290";
$dbname = "form_entriesdb";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect($host, $username, $password, $dbname);
//check connection if it is working or not
if (!$con)
{
die("Connection failed!" . mysqli_connect_error());
}
//This below line is a code to Send form entries to database
$sql = $con->prepare("INSERT INTO contactform_entries (name_fld, email_fld, msg_fld) VALUES (?, ?, ?)");
$sql->bind_param("sss", $name, $email, $message);
$sql->execute();
//connection closed.
$sql->close();
$con->close();
}
?>
And here's what displays my data, show.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$dbname = "form_entriesdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT id, name_fld, email_fld, msg_fld FROM contactform_entries";
$result = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name_fld"]. " " . $row["email_fld"]. " " . $row["msg_fld"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I ended up using .ajax instead of .post. I also changed my filename to index.php. I can't find the website where I got my code from, but here it is:
<!DOCTYPE html>
<html>
<head>
<title>Insert data in MySQL database using Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 60%;">
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
×
</div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="pwd">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Phone" name="phone">
</div>
<div class="form-group" >
<label for="pwd">City:</label>
<select name="city" id="city" class="form-control">
<option value="">Select</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
</select>
</div>
<input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
</form>
</div>
<p id="target">
</p>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
if(name!="" && email!="" && phone!="" && city!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
$('#target').load('show.php');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the fields !');
}
});
});
</script>
</body>
</html>
Here's save.php. It's the code that inserts data into the database:
<?php
include 'database.php';
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$sql = $con->prepare("INSERT INTO `crud`( `name`, `email`, `phone`, `city`) VALUES (?,?,?,?)");
$sql->bind_param("ssss", $name, $email, $phone, $city);
$rc = $sql->execute();
if (true===$rc) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
//connection closed.
$sql->close();
$con->close();
?>
Here is show.php:
<?php
include 'database.php';
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = "SELECT name, email, phone, city FROM crud";
$result = $con->query($query);
if ($result->num_rows > 0) {
// output data of each row
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["name"]. " " . $row["email"]. " " . $row["phone"]. " " . $row["city"]."<br>";
}
} else {
echo "0 results";
}
$result -> free_result();
$con->close();
?>
And here are the database connection details, database.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$db="school";
$con = mysqli_connect($servername, $username, $password,$db);
?>
The code posted is entirely functional.

unable to insert answer in database stored in textarea input using php

This file contains the code for search form:
search.php
<?php
session_start();
?>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<?php
echo"WELCOME ".strtoupper($_SESSION['user']);
?>
<form method="get" action="searched.php">
<label for="ques"></label>
<input type="text" name="title" id="title" placeholder="Search...">
<button type="submit" name="search"><i class="fa fa-search"></i></button>
</form>
<form method="post" action="question.php">
<button type="submit" name="ask_ques">Ask a Question</button>
</form>
</body>
</html>
This file gets the input from search bar and displays the title with question and answer if any. It also contains a comment box to answer the question:
searched.php
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<?php
$conn=new mysqli("localhost","khushank","sethi","q&a");
if($conn->connect_error){
echo "unable to connect";
}
if($_SERVER['REQUEST_METHOD']=='GET'){
if(isset($_GET['search'])){
$title=$_GET['title'];
$qsel=" SELECT title,qemail,ques FROM question WHERE title='$title' ";
if($qresult=$conn->query($qsel)){
if($qresult->num_rows==0){
header('location:question.php');
}
else{
while($qres=$qresult->fetch_assoc()){
echo "<strong>".ucfirst($qres['title'])."</strong><br><br>";
echo $qres['qemail'];
?>
<textarea cols="65" id="qdes"><?php echo $qres['ques']; ?></textarea><br><br>
<?php
$asel=" SELECT answer.aemail,answer.ans FROM question JOIN answer ON question.ques=answer.ques ";
if($aresult=$conn->query($asel)){
if($aresult->num_rows>0){
while($ares=$aresult->fetch_assoc()){
echo"Answer:";
?>
<textarea cols="65" id="ades"><?php echo $ares['ans']; ?></textarea><br><br>
<?php
}
}
?>
<form method="get" action="insertA.php?$ques='$qres['ques']'">
<label for="ans"><?php
echo $_SESSION['user'];
?></label>
<textarea cols="90" name="ans" placeholder="Your Answer"></textarea>
<input type="submit" name="comment" value="submit">
</form>
<?php
}
else{
echo "answer not selected";
}
}
}
}
else{
echo"not selected";
}
}
}
$conn->close();
?>
</body>
</html>
In this file answer is stored using GET method, but unable to get inserted into the database:
insert.php
<?php
require 'searched.php';
$conn=new mysqli("localhost","khushank","sethi","q&a");
if($conn->connect_error){
echo "unable to connect";
}
echo"connected";
if($_SERVER['REQUEST_METHOD']=='GET'){
if(isset($_GET['comment'])){
$ans=mysql_real_escape_string($_GET['ans']);
$username=$_SESSION['user'];
//$ques=$_GET['$ques'];
$insa=" INSERT INTO answer(aemail,ans) VALUES('$username','$ans') " ;
if($conn->query($insa)){
echo"inserted";
echo"<script type='text/javascript'>".'alert("your answer is posted successfully");
</script>';
}
else{
echo"not inserted";
}
}
}
else{
echo"1";
}
$conn->close();
?>
I'm unable to insert the values stored in $ans.
the problem is you can not write php direct into html. watch your search.php form tag. use this.
<form method="get" action="insert.php?<?php echo "$ques='".$qres['ques']."'">
and one more thing your page name is just insert.php not insertA.php
Here is the corrected solution to your problem. Though I do not see your schema, it looks like it is a bit wrong since you are joining the table using question field which according to your question is likely of string datatype. So here is the proposed db structure:
Question table:
DROP TABLE IF EXISTS `question`;
CREATE TABLE IF NOT EXISTS `question` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`qemail` varchar(100) NOT NULL,
`que` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `question`
--
INSERT INTO `question` (`id`, `title`, `qemail`, `que`) VALUES
(1, 'Physics', 'thanga#gmail.com', 'This is the quesiotn');
COMMIT;
Answer Table:
CREATE TABLE IF NOT EXISTS `answer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`questionid` int(11) NOT NULL,
`aemail` varchar(100) NOT NULL,
`ans` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `answer`
--
INSERT INTO `answer` (`id`, `questionid`, `aemail`, `ans`) VALUES
(1, 1, 'thanga#gmail.com', 'My answer is here'),
(2, 1, 'Khuskant', 'The new answer');
We add the question id in the answer table as we need it for joining both tables. It means we relation using the question id.
Change search.php to this:
<?php
session_start();
$_SESSION['user']='Khuskant'
?>
<html>
<head></head>
<body>
<?php
echo"WELCOME ".strtoupper($_SESSION['user']);
?>
<form method="get" action="searched.php">
<label for="ques"></label>
<input type="text" name="title" id="title" placeholder="Search...">
<button type="submit" name="search" value="token"><i class="fa fa-search"></i></button>
</form>
<form method="post" action="question.php">
<button type="submit" name="ask_ques">Ask a Question</button>
</form>
</body>
</html>
When you submit the above form, you either go to question.php or searched.php depending on the availability of the search term in the db. If you want match the search term with the exact data stored in the question table, the following code will do:
searched.php
<?php
session_start();
require_once "dbconnect.php";
?>
<html>
<head>
</head>
<body class="content">
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
if(isset($_GET['search'])){
$title= filter_var($_GET['title'],FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT id, title, qemail, que
FROM question WHERE title=?");
$stmt->bind_param("s", $title);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows==0){
header('location:question.php');
}else{
while ($qres = $result->fetch_array(MYSQLI_ASSOC)) {
echo "<strong>".ucfirst($qres['title'])."</strong><br><br>";
echo $qres['qemail']; ?>
<textarea cols="65" id="qdes"><?php echo $qres['que']; ?></textarea>
<?php
$qid = $qres['id'];
$aresult = $conn->query("SELECT answer.aemail, answer.ans
FROM question
LEFT JOIN answer ON question.id=answer.questionid
WHERE question.id=$qid");
if($aresult->num_rows>0){
while($ares = $aresult->fetch_assoc()){
echo"<br>Answer:"; ?>
<textarea cols="65" id="ades"><?php echo $ares['ans']; ?></textarea><br><br>
<?php } } ?>
<form method="get" action="insert.php">
<label for="ans"><?php echo $_SESSION['user'];?></label>
<textarea cols="90" name="ans" placeholder="Your Answer"></textarea>
<input type="hidden" name="qid" value="<?php echo $qid;?>">
<input type="submit" name="comment" value="submit">
</form>
<?php
}
}
}
} ?>
</body>
</html>
if you want a partial match, you have to change this part of the code:
$stmt = $conn->prepare("SELECT id, title, qemail, que
FROM question WHERE title=?");
$stmt->bind_param("s", $title);
to
$stmt = $conn->prepare("SELECT id, title, qemail, que
FROM question WHERE title LIKE ?");
$stmt->bind_param("s", $title."%");
Change the insert.php to:
<?php
session_start();
require 'dbconnect.php';
if($_SERVER['REQUEST_METHOD']=='GET'){
if(isset($_GET['comment'])){
$ans=filter_var($_GET['ans'], FILTER_SANITIZE_STRING);
$qid=filter_var($_GET['qid'], FILTER_SANITIZE_NUMBER_INT);
$username=$_SESSION['user'];
$insa= $conn->prepare("INSERT INTO answer(questionid, aemail, ans) VALUES(?,?,?)");
$insa->bind_param('iss', $qid, $username, $ans);
$insa->execute();
if($insa->affected_rows>0){
echo $insa->affected_rows." rows inserted";
exit;
} else{
echo"not inserted";
exit;
}
}
}
else{
echo "1";
}
$conn->close();
?>
dbconnect.php
$conn = new mysqli("localhost", "user", "pass", "testdb");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
Put them all in the same directory, it will works. Hope this helps you.

PHP form, converting input field into a drop down list

The below code is a simple form that is sending the data that is inputted to my local database.
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="school" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
</body>
</html>
The issue that I am finding is that I am trying to change the Student City input field into a drop down where the values is retrieve from the database and put into a drop down list for a new user to select.
Could someone advise on what needs to be done please.
i am trying to use the below code and send the below list to my database.
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
<option value="Mexico">Mexico</option>
but i am finding it hard to send the these values to the database with my above code as well as where to place this code.
As a rough example of how you could build the dropdown menu using data from your db this should give you the general idea perhaps.
/* store formatted menu options in temp array */
$html=array();
/* query db to find schools/cities */
$sql='select distinct `student_school` from `students` order by `student_school`';
$res=$mysqli_query( $conn, $sql );
/* process recordset and store options */
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
$html[]="<option value='{$rs->student_school}'>{$rs->student_school}";
}
}
/* render menu */
echo "<select name='stu_city'>", implode( PHP_EOL, $html ), "</select>";
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
if ($conn->query ( $sql ) === TRUE) {
$cities = ... // build the cities from the query result
} else {
$cities = '<option value="none">No cities found</option>' ;
}
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple><?php echo $cities; ?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>
Use the Select tag: Lets say you hav a column in your database with Student City, like this, lets say the database field is called city
City 1
City 2
City 3
Step 1: Query the database and fetch all the Cities
$sql = "SELECT city FROM table_name";
$result = $conn->query($sql);
Then you come to your dropdown:
<select name="stu_city" id="..." required>
<?php
while($cities = $conn->fetch_array($result){
extract($cities);
echo "<option value='...'>$city</option>";
}
?>
</select>
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
$result = $conn->query ( $sql );
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple>
<?php
if ($result == TRUE) {
while($cities = $conn->fetch_array($result)){
extract($cities);
echo "<option value=''>$city_name</option>";
}
}
else {
echo "<option value='none'>No cities found</option>";
}
?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>

Search info from SQL Database

I have creacted an SQL Database. I succsess fully insert data into database, but i want to search from database.
HTML
<body>
INSERT AREA
<br>
<form action="demo.php" method="post"/>
<p>imei: <input type="text" name="input1"/> </p>
<select name="input2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<br>
<input type="submit" src="submit.png" alt="Submit Form" />
</form>
Search AREA
<br>
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
</body>
demo.php
<?php
define('DB_NAME', '#');
define('DB_USER', '#');
define('DB_PASSWORD', 'mypass');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
$value2 = $_POST['input2'];
$sql = "INSERT INTO demo (input1, input2) VALUES ('$value', '$value2')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
So all these work perfect , i insert data to SQL Database fine, but check the next php code for search, isn't return any info it just open with-out return value. *i have wipe the database info.
Database name : demo
Host name :localhost
form.php
<?php
$db_hostname = 'localhost';
$db_username = 'my username';
$db_password = 'my pass';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="demo.php" method="post"/>
<p>imei: <input type="text" name="input1"/> </p>
<select name="input2">
<option value="1">111111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">33333333333333333</option>
<option value="4">4444444444444444</option>
</select>
<br>
<br>
<input type="image" src="submit.png" alt="Submit Form" />
</form>
<br>
<form action="form.php" method="post">
<input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM demeo WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['input1'];
echo '<br /> Description: '.$row['input2'];
}
}
?>
</body>
</html>
By looking at your first example, it seems that in the second one, your table and column names are incorrect.
Replace your current query:
SELECT * FROM demeo WHERE Description LIKE '%".$term."%'
With this query:
SELECT * FROM demo WHERE input2 LIKE '%".$term."%'}
Also consider the suggestions of the other users to avoid sql injections.

wrong value stored in database

I am trying to store form value in database but wrong value is stored in database for mobilenumber field in my table. In table, I have the following 4 fields.
id (auto increment),
mobilenumber,
operator,
date.
Value displayed correctly when I do echo.
But while storing mobile number in database table, I am not getting the same value of mobilenumber field.
I have the following code.
home page
<?php include "header.php"?>
<body>
<div class="form-group">
<form name="myForm" action="invite.php" method="post" class="elegant-aero" onsubmit="return ValidateForm()" >
<h1> Congratulations. You have been invited to win Rs 148 Recharge.
<span>Please fill all the details to get a Rs 148 Recharge.</span>
</h1>
<label>
<span>Mobile Number</span>
<input name="Mobile" id="mob" type="text" placeholder="Prepaid Mobile Number" required />
</label>
<label>
<span>Operator</span><select name="Operator">
<option value="Select Operator">Select Operator</option>
<option value="Bsnl">BSNL</option>
<option value="Airtel">Airtel</option>
<option value="reliance">Reliance</option>
<option value="Vodafone">Vodafone</option>
<option value="Videocone">Videocone</option>
<option value="Aircel">Aircel</option>
<option value="Telenor">Telenor</option>
<option value="Idea">Idea</option>
<option value="Tataindicom">Tataindicom</option>
<option value="other">Other</option>
</select>
</label>
<label>
<span> </span>
<input type="submit" class="button" value="Proceed To Recharge" />
</label>
</form>
<div>
</body>
<?php include "footer.php" ?>
</html>
page 2
<html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "recharge_project";
/**$mobile = $_POST['Mobile'];
$operator = $_POST['Operator'];
**/
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST[Mobile]', '$_POST[Operator]')";
if ($conn->query($sql) === TRUE) {
echo "datainserteed";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php include "header.php"?>
<body xmlns="http://www.w3.org/1999/html">
<div class="form-group">
<form class="elegant-aero" >
<p> Invite your 10 active <span style="color:#FF0000"> WhatsApp Friends</span> <!-- and 3 <span style="color:#FF0000">WhatsApp Groups </span>-->to claim your recharge
</p>
<label>
<a class="button1" href="whatsapp://send?text=http://rechargetoday.net || Super Promo offer. Get Rs 148 free recharge. Visit above link to get your recharge.NOTE :Offer valid across India!!" onclick="return myFunction()" >Invite</a>
</br>
</label>
<?php echo"</br>";?>
<label>
<a name="finish" type="submit" class="button2" onclick="return aboveTen()">Finished- Inviting 10 friends </a>
</label>
<label>
</label>
</form>
<div>
</body>
</html>
I have the following JS code.
var invite = 0;
function ValidateForm()
{
var fld= document.forms["myForm"]["Mobile"].value;
var phoneno = /^\d{10}$/;
if(fld.match(phoneno))
{
return true;
}
else
{
alert("Please enter valid number");
return false;
}
}
function myFunction(){ invite ++; }
When I echoed $sql, I got the below query.
INSERT INTO customer (mobilenumber, mobileoperator) VALUES ( 8574968578, 'Vodafone')
Try using $sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST['Mobile']', '$_POST['Operator']')"; rather
$sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST[Mobile]', '$_POST[Operator]')";.

Categories