JQuery Autocomplete Form from Database fails - javascript

I'm following a tutorial (http://www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step) and I try to do this but with a local phpmyadmin database, using Xampp installed on my PC.
I have a table called cars with the columns id and name, I filled in 2 entries, however, the autocomplete doesn't work, in fact, I don't get any suggestions below my form. Since I can't bother you with all the JS files, maybe someone can explain what this precisely does, especially the last while function, because I think here lies the problem:
$sql = 'SELECT id, name FROM cars';
for($i = 0; $i < $p; $i++) {
$sql .= ' AND name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}
while($row = $rs->fetch_assoc()) {
$a_json_row["id"] = $row['id'];
$a_json_row["value"] = $row['name'];
$a_json_row["label"] = $row['name'];
array_push($a_json, $a_json_row);
}

You are not declaring WHERE in your SQL statement. Query likely failing, yielding zero autocomplete options.
$sql = 'SELECT id, name FROM cars';
for($i = 0; $i < $p; $i++) {
if ($i == 0){ $sql.= " WHERE"; } // THIS LINE HERE
$sql .= ' AND name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}

My Solution to this Problem:
while($cars=mysql_fetch_array($query)){
$json[]=array(
'value'=>$cars["name"],
'label'=>$cars["name"]
);
}
echo json_encode($json);

Related

PHP echo selected value from html dropdown list

In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().

PHP Javascript Array

Hi I'm a novice PHP developer to say the least and I'm pretty stuck.
I'm trying to get the below code working I know I need a foreach loop or similar but I'm way out of my depth, I'm really not sure how to get this working, I know to most of you this is basic stuff but I'm lost.
Basically this is a receipt when a tab is settled. It searches the MySql Database for the relevant items and should print them on the receipt.
I know the MySql Query is not linked to the output at the bottom but I don't know how to do it.
<html lang="en">
<head>
<title>Receipt</title>
</head>
<body>
<?php
$invoicenum = $_POST['invoicenum'];
$name = $_POST['name'];
$netrev=$invoicenum - 1;
?>
Items:
<?
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
$result = array();
while($row = mysql_fetch_array($itemQuery))
{
$result[] = $row['itemname'];
}
echo json_encode($result);
$amounts = json_decode($result['amounts']);
$items = json_decode($result['items']);
$prices = json_decode($result['prices']);
?>
<br>
<?
for ($i = 0; $i < count($items); $i++)
{
echo $amounts[$i] . "x " . $items[$i] . " - " . $prices[$i] . "<br>";
}
?>
</body>
</html>
I've removed code that isn't relevant to this array, if you can help I'd be forever grateful.
no need of encode and decode.
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
while($row = mysql_fetch_array($itemQuery))
{
echo $row['amounts'] . "x " . $row['items'] . " - " . $row['prices'] . "<br>";
}
?>
Forget all json_decode/encode after filling $result then:
First do:
$result[] = $row;
Then:
foreach ($result as $set){
echo $set['amount'] . "x " . $set['itemname'] . " - " . $set['price'] . "<br>";
#do var_dump($set); here for checking the keys
}

Dynamically generate JavaScript using PHP

I have this JavaScript code that is working well:
var lookup = {
"dog-black":{url:'images/dog-black.jpg'},
"dog-white":{url:'images/dog-white.jpg'},
"cat-black":{url:'images/cat-black.jpg'},
"cat-white":{url:'images/cat-white.jpg'}
};
I'm tring to generate same code dynamically using PHP to have lines as much as there in the DB, like this:
var lookup = {
<?php
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '"'.$row['name'].'":{url:images/'.$row['name'].'.jpg';
}
} else {echo "No records";}
?>
};
I tried to define the php code as string using quotes or heredoc and alert the string variable, but seems like the script is not excuted
note: i'm already connected to the DB before this part of code and pass data from/to it.
Don't try to echo this out manually. What you can do is build the same structure in PHP, then use json_encode.
JSON is actually valid JavaScript code, so it will work.
Try it like this:
<?php
$lookup = array();
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$lookup[$row['name']] = array('url' => 'images/'.$row['name'].'.jpg');
}
}
else {
//echo "No records";
}
?>
var lookup = <?=json_encode($lookup); ?>;
There seems to be a mistake in the echo in the while loop. You're not closing the string correctly, it is missing the closing part },. Which should look something like this:
echo '"'.$row['name'].'":{url:"images/'.$row['name'].'.jpg"},';

How to add validation(javascript) in php?

let say that, i want to my change password in php code then it will validate by the use of javascript. before it return to my index page or it will popup on index page. how can i do it? any trick that you can suggest? :)
<?php
include('config2.php');
error_reporting(E_ERROR | E_PARSE);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$val = $_GET['val1'];
session_start();
$ak = $_SESSION['autokey'];
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
header("location:index");
?>
thanks in advance :)
You could change your code block like this..
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
if(mysql_affected_rows())
{
echo "<script>alert('Password was successfully changed !');</script>";
echo "<script>window.location='index.php'</script>";
} else
{
echo "<script>alert('Password was not changed');</script>";
echo "<script>window.location='index.php'</script>";
}
As the comment says.. You are mixing up mysql_* and mysqli_*. Change that first.
Sidenote: Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources