I am suing autocomplete to display values from database.
The file is as follows:
autocomplete.php
<?php
require_once "../includes/conf.php";
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
//$mysqli=mysql_connect('localhost','root','','autofield') or die("Database Error");
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['vName']." </n>".$row['id'];
}
}
?>
The above file retuens the name that will be displayed in the text filed. Along with that I would like to pass id as hidden field so that I can process the data in php
How should I go about it?
You can make use of input type hidden for this purpose.
<input type="hidden" value=".$row['id']."/>
try this:
$array = array();
while($row=mysql_fetch_array($result))
{
array_push($array ,array("value"=>$row['id'],"label"=>$row['vName']));
}
and in jquery code:
terms.push( ui.item.label );
$( "#hidtextboxid" ).val( ui.item.value);
make sure you create one hidden field in your code.
check this:
how to pass hidden id using json in jquery ui autocomplete?
i dont want to answer your question with mysql_query for two reasons:
1. mysql_query official status is Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
2. it is vulnerable to SQL injection, see How can I prevent SQL injection in PHP?
use PDO (PHP Data Objects ) instead, it is secured and it is object-oriented
here are some tutorials to master this in 12 videos http://www.youtube.com/watch?v=XQjKkNiByCk
replace your MySQL instance with this
// instance of pdo
$config['db'] = array
(
'host' => '',
'username' => '',
'password' => '',
'dbname' => ''
);
$dbh = new PDO('mysql:host=' . $config['db']['host'] .
';dbname=' . $config['db']['dbname'],
$config['db']['username'],
$config['db']['password']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
global $dbh;
//dbh is just a custom name for the object you can name it database
edit the credentials, next lets query your code, if the instance is not on the same file ie the connection script is being included then call upon global $dbh; before you start your sql so you bring the object to the current file otherwise
so your code will look like this
<?php
global $dbh;
//lets prepare the statement using : to input what ever variables we need to (securely)
$displayData= $dbh->prepare("SELECT vName,id FROM employee WHERE vName LIKE :my_data ORDER BY vName");
$displayData->bindValue(':my_data', $my_data , PDO::PARAM_STR);
//then we execute the code
$displayData->execute();
//store the result in array
$result = $displayData->fetchAll();
print_r($result); //take a look at the structured
//depending on the structure echoing could be like **echo $result[0][theIdYouTrynaGet];**
?>
And how would I retrieve it in the other page then?
<html>
<?php
include_once '/*the path of your file where the above is happening*/';
<input type="hidden" value="<?php echo $result['pass in your parameters'] ?>"/>
?>
<html>
Related
Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.
I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.
I'm using php to fetch a db query that I want to make a table from. I want to put the query results into a json object and then use javascript from there to output the results into a table. I used json_encode to create the json object in php.
I'm fairly new to javascript so I'm a little confused as to how I can send the json object I've created to javascript and then output the results using javascript? Should I include the javascript in the same file as the php page or a different one?
If you can explain what you're doing that would be awesome because I really want to know what's going on at each step.
Here's what I have so far:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
Update:
So I went ahead and made xyz.php my backend page and made a main.php for displaying the results. I started off with this sample function to make sure my jquery was fetching the results from the xyz.php page. Now, I don't know how to display the results in a table using jquery.
Here's what I did for my main.php page:
<?php
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("xyz.php");
});
});
</script>
<div id="div1"></div>
<button>Show JSON Results</button>
What you can do is:
Make the PHP file as backend. So that,
xyz.php:
// PUT YOUR CODE HERE
$sql = "SELECT Name,
Location,
ID,
Price
From ProdTable
where ID>=2000";
$encode=array();
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
?>
AND it should be accessible from the URL.
For example: xyz.php?id=2000
Now, on the page from where you want to populate this data, use jQuery
$.post
And manipulate this json.
This will ensure your page loads faster as dynamic data is getting populated after initial page load.
Hope it works for you.
I have create multiple row by using javascript. Now how to save these row in mysql. I already using some type of code, its not working. here my code is
[http://jsfiddle.net/bb2pJ/]
and php code for adding these value.
`
include "config.php";
if(isset($_POST['submit']))
{
foreach ($_POST['code1'] as $key => $value)
{
$code1 = $_POST["code1"][$key];
$product1 = $_POST["product_name1"][$key];
$qty = $_POST["quantity1"][$key];
$rate = $_POST["amount_name1"][$key];
$total = $_POST["total_name1"][$key];
$sql = mysql_query("insert into testing(code,product,qty,rate,total)values('$code1','$product1','$qty1','$rate1','$total1')")or die(mysql_error());
}
}
?>`
From you Js fiddle code, you are trying to post array of values for each field (ie code, proddname, ...).
How are submitting these values? If not passing through ajax post, then you need to declare fields names like code[], product_name[] ... as array for all fields so they will be submitted as array.
Rest code you have writtten above should work by using proper field name like code for code[] ... .
Please put proper spacing between your keywords and values/fieldname in your insert into.. statement.
I have used jquery ajax which initiates on click of a button , and on click of it a variable passes to the php script that the jquery post is using. However when i try to append the return data on javascript alert() method it returns the php script's html contents instead rather than rendering it out. Can anyone assit me on this?
<?php
$var = $_POST['var'];
$sql = mysql_query("select * from racers Where style = '$var'");
while ($r = mysql_fetch_assoc($sql))
{
$name = $r['rName'];
echo '<tr><td>'.$name.'</td></tr>';
}
?>
You have a syntax error, try this;
<?php
$var = $_POST['var'];
$sql = mysql_query("select * from racers Where style = '$var'");
while ($r = mysql_fetch_assoc($sql))
{
$name = $r['rName'];
echo '<tr><td>'.$name.'</td></tr>';
}
?>
change sql_query to mysql_query
I assume you are using Apache (as most of the PHP configs do).
Did you check your Apache configuration. I guess it must be configured to process PHP's as scripts. Otherwise it returns it as it is without parsing