JQuery Autocomplete suggestion retrieved from database - php

I need to to do autocomplete suggestion for my thesis and the data should be retrieved from database. here is my code but it doesn't work! this is my html file.
<!DOCTYPE HTML>
<html>
<head>
<title>Fetching saved records</title>
<script src="jquery-3.2.1.js"></script>
<script src="typeahead.js"></script>
<script type="text/javascript"> </script>
<script>
$(document).ready(function() {
$('input.city').typeahead({
name: 'city',
remote: 'samp5.php?query=%QUERY'
});
})
</script>
</head>
<body>
<form>
Enter the name to search data:<br/>
<input type="text" name="city" id="city" class="city"
autocomplete="off">
<input type="submit" name="find" id="find" value="Find Data"/>
</form>
</body>
</html>
and this is my php file.
<?php
include "connection.php";
if(isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query("SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_array($sql)) {
$array[] = array (
'label' => $row['city'].', '.$row['area'],
'value' => $row['city'],
);
}
echo json_encode ($array);
}
?>
I don't know why it doesn't work cause there's no error in my codes.
console errors

mysqli_query() requires 2 arguments, the connection and the query, i.e.:
$sql = mysqli_query($connection, "SELECT city, area FROM tbl_loc WHERE city LIKE '%{$query}%' OR area LIKE '%{$query}%'")
Warning!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
You may want to...
Add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add error checking, such as or die(mysqli_error($connection)) to your queries and other database operations. If not, you can typically find the issues in your current error logs.

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.

Writing to database from CKEDITOR

I'm trying to write to a database using CKEditor.. when I press submit it dies and says localhost is currently unable to handle this request.
HTTP ERROR 500
I only want to save the textarea into a row in database so I can then read the row on to another page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Classic editor replacing a textarea</title>
<script src="http://cdn.ckeditor.com/4.6.0/standard-all/ckeditor.js"></script>
</head>
<body>
<form id="editor1" action="save.php" method="post" >
<textarea cols="80" id="editor1" name="editor1" rows="10">
</textarea>
<p>
<input type="submit" value="Submit">
</p>
</form>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
PHP script
<?php
if(isset($_POST['submit']))
{
// Putting data from form into variables to be manipulated
$text = $_POST['editor1'];
$conn = mysql_connect("localhost","root","root") or die ("Can't connect");
mysql_select_db("managerMessage",$conn);
// Getting the form variables and then placing their values into the MySQL table
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
}
?>
You are not concatenating the value correctly in this statement and also text data in a query like this should be wrapped in quotes
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
This is a corrected verion of your code
mysql_query("INSERT INTO text
(textarea)
VALUES ('" . mysql_real_escape_string($text) . "')");
A simpler piece of code would be to read and probably maintain would be
$t = mysql_real_escape_string($text);
mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
I would be remiss if I did not remind you that
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
EDIT RE: not saving the data to the database
Add some error checking to your code like so:
$t = mysql_real_escape_string($text);
$result = mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
if ( ! $result ) {
echo mysql_error();
exit;
}
Once you know the error, if one exists, you can start work on fixing it.

PHP form submission with refreshing

first time posting on here so I apologise for any bad habits.
I recently started an online youtube tutorial on php and how to create a blog.
I ended up getting occupied with other things and have come back to try an finish what I started and 2 things have happened. 1: my tutorials have been deleted off youtube(must of been a copyrright issue) and second I've completely forgot the method used. I assume if I was a seasoned coder this would be easy to decipher but I'm having no luck after trying for days now.
This code is for the submission form for my blog. The blog is working in the sense of if I manually input my HTML into the SQL database but all I seem to get if I use this form is a refresh of the submission page with all the information gone. No information is added to the database.
Anybody have an idea?I had a good search around the site but I ran into a dead end due to my lack of knowledge on what I was actually searching for (lots of solutions regarding javascript)
All help will be appreciated.
Sincerely
SGT Noob
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit']))
if ($_POST['submit']) {
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
include_once("../admin/connection.php");
$sql = "INSERT INTO `posts` (Post_Title, Post_Content, Post_Date)
VALUES ('$title','$content','$date')";
mysqli_query($dbcon,$sql);
echo "Post has been added to the database";
}
else {
header('Location: index.php');
die();
}
?>
<html>
<div>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<title> Insert Post </title>
</head>
<div>
<body>
<div id= 'cmssubmissionform'>
<form action="" method="post">
<p>
<h1> Post Title</h1>
<input type="text" name= "Post_Title"/>
</p>
<h1> Post Date</h1>
<input type="text" name= "Post_Date"/>
</p>
<p>
<h1>Post Content </h1>
<textarea name="Post_Content"></textarea>
<script>
CKEDITOR.replace( 'Post_Content' );
</script>
</p>
<p>
<input type = "submit" value="submit" />
</p>
</form>
</div>
</div>
</div>
</body>
try this
in your from change to
<input type = "submit" value="submit" name="submit"/>
You forgot to put the name attribute
The php
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include_once("../admin/connection.php");
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit'])){
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
$sql = "INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date')";
if(mysqli_query($dbcon,$sql)){
echo "Post has been added to the database";
}else{
header('Location: index.php');
die();
}
}
?>
Note I also changed your SQL statement to
INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date
Notice the back ticks for the table fields
Replace
if (isset($_POST['submit']))
if ($_POST['submit']) {
with
if (isset($_POST['submit'])) {
and then replace
<input type = "submit" value="submit" />
with
<input type ="submit" name="submit" value="submit" />
However, at this stage I would highly suggest starting over with a different tutorial.
Also, as has been mentioned in the comments, whenever you take arguments from a user and put them into a database query, you must absolutely make sure that the strings do not manipulate the query (imagine someone wrote 0'; DROP TABLE `blog`; -- in the date field (and "blog" were the name of your blog post table). That would be quite catastrophic, wouldn't it?
So when you handle input data, either use the prepare and bind methods of the mysqli package, or pass the strings through the mysqli_real_escape_string() function first.

PHP search script to pull customer data from mysql

I am trying to build a simple search script in my own customer portal, I am trying to build it to search by their phone ESN. I am not very experienced with php, so I am probably missing something small, or making a small mistake.
anyway, when you type in any esn of a phone and hit search, it shows no results at all. here is the simple script I am working with
<?php
$dbserv='********';
$dbuser='********';
$dbpass='********';
$dbdata='********';
$link = mysql_connect($dbserv, $dbuser, $dbpass);
if (!$link) { die('Could not connect: ' . mysql_error());}mysql_select_db($dbdata);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="esn" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['esn'])) {
$esn = mysql_real_escape_string($_REQUEST['esn']);
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'ESN: ' .$row['phoneserial'].'<br>';
}
}
?>
</body>
</html>
I noticed I made an error earlier in this line
$esn = mysql_real_escape_string($_REQUEST['esn']);
I had it like this instead
$term = mysql_real_escape_string($_REQUEST['esn']);
and then when you typed a 14 digit esn starting with A10000, it would actually show every esn in our database instead of the one that was searched for and i don't know why.
Forgive me if this is lame, still trying to learn
If $esn was undefined, you'd be searching for a pure wildcard (%%), which would match every possible record. Not that surprising when you look at this code:
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";
Just remove the $esn since you didn't define $esn and instead used $term.
You really shouldn't use mysql_ functions anymore. Learn how to use mysqli or PDO and prepared statements rather than escape string functions.
if u want to find only ONE, strict match, you should replace your query with this
$sql = "SELECT * FROM phones where phoneserial = '{$esn}'";
Don't use mysql, use Mysqli
MySQL extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0
Final well form code is
<?php
$dbserv='********';
$dbuser='********';
$dbpass='********';
$dbdata='********';
$link = mysqli_connect($dbserv, $dbuser, $dbpass,$dbdata);
if (!empty($_POST['esn'])) {
$esn = mysqli_real_escape_string($link$_POST['esn']);
$sql = "SELECT * FROM phones where phoneserial LIKE '%".$esn."%'";;
$r_query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($r_query))
{
echo 'ESN: ' .$row['phoneserial'].'<br>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="esn" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Need help submitting my form data into database

OK, let me start off by saying im an amateur, so all your help is really appreciated.
OK, I have a form, called 'skills.php' and on this form, you enter the following fields 'Skills_ID, Employee_ID, First_name, Last_name and Skill'. I have used java so when you select employee_ID, the name fields change to what employee that is (linked to employee table).
HOWEVER, since i have added this function, i can not save my form data into my database. Maby i accidently deleted a line of code when implementing the java function. Can someone help me figure it out? below is my form 'Skill.php':
<html>
<?php
// Connecting to database
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Online Jquery -->
<title>Skill</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Employee Skill</h1>
<form action="insertskill.php" method="post">
<div>
<p>
Skill ID:
<input type="text" name="Training_ID">
</p>
<p>
Employee ID:
<select id="Employee_ID">
<option value="">Select one</option>
<?php
$st = $pdo->prepare("SELECT Employee_ID FROM Employee");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
?><option value="<?php echo $row ['Employee_ID']; ?>"><?php echo $row ['Employee_ID']; ?></option><?php
}
?>
</select>
<p>
First name:
<input type="text" name="First_name" id="First_name">
</p>
<p>
Last name:
<input type="text" name="Last_name" id="Last_name">
</p>
<p>
<p>Skill: <select name="Skill">
<option value="">Select...</option>
<option value="Checkouts">Checkouts</option>
<option value="Fresh goods">Fresh goods</option>
<option value="Dry goods">Dry goods</option>
<option value="Fruit & Veg">Fruit & Veg</option>
<option value="Operations">Operations</option>
</select>
</p>
<input type="submit">
<INPUT Type="BUTTON" VALUE="Back" ONCLICK="window.location.href='index.html'">
</form>
</div>
<script type="text/javascript">
$(function() { // This code will be executed when DOM is ready
$('#Employee_ID').change(function() {
var $self = $(this); // jQuery object with the select inside
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
})
});
})
</script>
</body>
</html>
And here is the code used when the submit button is pressed 'insertskill.php':
<?php
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
?>
Just by looking at this code imn pretty sure i might of accidently deleted the coding to insert it into database, HOWEVER i dont know how to fix it :( can someone help? much appreciated! Thanks in advance
in "insertskill.php" line 6:
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
You're performing a SELECT query (read), sounds to me more like you wanted an INSERT query (write).
An INSERT statement in your case would be something similar to:
$st = $pdo->prepare("INSERT INTO Employee (Training_Id,Employee_Id,First_Name,Last_Name,Skill) VALUES (:training_id,:employee_id,:first_name,:last_name,:skill)")
$st->execute(array(':training_id' => $training_id, ':employee_id' => ...));
First, watch out. Java is not JavaScript!
And you're right, you removed the INSERT lines. There are several articles on the web about how to do that. Here is one. Just google PDO Insert for more results.
You should put these INSERT commands in your insertskill.php file and create another one, maybe fetchName.php or something like that, with the code that you presented to return first and last name for an employee based on its id, and use that in your JavaScript $.change() function. It doesn't make sense for a file called insertskill.php to fetch data.
And your forgot to specify that you're expecting a JSON in your $.post() command. Do that instead:
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
}, 'json'); // Here!
First thing to say is that you are NOT using Java. You are using JavaScript (actually ECMAScript which is VERY VERY different from Java.
Next, you are correct, that there is now no INSERT statement there at all, you will need to write one to insert whatever data you want to insert.
HOWEVER, you also need to somehow tell the difference between when insertskill.php is called for an Ajax request (to get the names for the form) and when it is called to insert the data. So on your Javascript (jQuery I guess) request, you could change the url to:
$.post("insertskill.php?ajax"
and then in insertskill.php do:
if(isset($_GET['ajax'])) {
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
}
else {
// Do the insert statement stuff...
}

Categories