Can someone please take a look at this link and let me know why the auto complete text box is not functioning?
What I have is a Table called Brangays in a MySQL datadabase "157400X_XXXXXX which contains:
I have these files as PHP files aswell
1-:Get_Auto1.php
<?php
// Database Connection
include("configPDO.php");
// Query to get the usable suggestions
$likeString = '%' . $_GET['term'] . '%';
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Barangay FROM Barangays WHERE Barangay LIKE :likeString");
// bind parameters, Named parameters always start with colon(:)
$STM->bindParam(':likeString', $likeString);
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
// Deifne array for category.
$Category_array = array();
// Use for each loop to push all results in category array.
foreach($STMrecords as $row)
{
// Store all values in $result variable.
$result = $row[0];
// push all values in category array using array_push function which treats array as a stack, and pushes the passed variables onto the end of array.
array_push($Category_array, $result);
}
// encode it using json_encode which returns a string containing the JSON representation of value.
$json = json_encode($Category_array);
// echo it for getting it using Ajax function explained above.
echo $json;
?>
2- configPDO.php
<?php
// mysql hostname
$hostname = 'fdb3.xxxxxxx.net';
// mysql username
$username = '15740xx_xxxxxx';
// mysql password
$password = 'xxxxxxx';
// Database Connection using PDO with Try Catch Statements
try {
$dbh = new PDO("mysql:host=$hostname;dbname=1xxxxx_xxxxxx", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Related
I am a novice when it comes to working with JSON/PHP. I have been trying to get this to work based off this answer.
How to generate .json file with PHP?
I am trying to query a MySQL database to output it in a JSON format without having it write to a new file I.E. file.json since I am pulling dynamic data. I can create a script that creates a json array but, I need the output in a JSON format. The script I have been working with below from the example link above connects to the DB but, it is not populating with data. It just gives me this output. I added the DB connection check to check if the script was connecting to the DB.
Connected successfully{"streamers":[]}
This is the code I am currently working with. Is there anyone who could tell me what I am missing and could improve on. DB info removed for security reasons.
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
//Prepare the query for analyzing
$sql=$db->prepare('select * from maintable');
$response = array();
$streamers = array();
$result=mysql_query($sql);
while($sql=mysql_fetch_array($result))
{
$displayname=$row['DisplayName'];
$streamkey=$row['StreamKey'];
$streamers[] = array('DisplayName'=> $displayname, 'StreamKey'=> $streamkey);
}
$response['streamers'] = $streamers;
echo stripslashes(json_encode($response));
?>
-Thanks!
First, use PDO only. No mysql_* functions.
Then your code should look like this:
$pdo = new PDO('mysql:host=...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$result = $pdo->query('SELECT DisplayName, StreamKey FROM ...');
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json;charset=utf-8');
echo json_encode(['streamers' => $rows],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
The PDO::ERRMODE_EXCEPTION sets PDO to throw all errors as exceptions, so they can be handled in an easy and consistent way.
The PDO::FETCH_ASSOC sets fetchAll() to return rows as arrays where column names are used as array keys.
The json_encode() will take care of producing a valid JSON output. Since you are not embedding JSON into HTML, there is no need for escaped slashes and we will make it nicely indented for easier debugging.
So as I said in a comment, the problem is probably that "$row" is not initialized. It should probably be:
while($row=mysql_fetch_array($result))
Also, you used mysql_ functions which are not compatible with PDO. You should do your request using $db->query.
As you asked for suggestions, I may give you a trick that I use.
I think that it's a lot of code for just retrieving a table that is basically the content of the result of your query (in $result). And I guess you have similar code for almost every request. So what I do in general is that I build a generic function called extractResult that directly makes an array of lines from the result of a query.
Here is the function:
/**
* Extract a php array from the result of a db query.
* This result can be directly parsed in JSON for instance.
*/
function extractResult($res) {
$arr = array();
while($line = $res->fetch()) {
$count = count($line)/2;
for ($i=0; $i<$count; $i++) {
unset($line[$i]);
}
array_push($arr, $line);
}
return $arr;
}
Note: the for loop with the "unset" is made to remove the entries with digits. What's returned by a fetch is something like this:
Array("DisplayName" => "Loulou", 0 =>"Loulou", "StreamKey" => 12, 1 => 12)
So it removes the numerical duplicates.
So you could use it like this and your code becomes way lighter:
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
$result=$db->query('select display_name AS DisplayName, stream_key AS StreamKey from maintable');
$response = array();
$response['streamers'] = extractResult($result);
echo json_encode($response);
?>
Note that you have to specify the columns name that you want directly in the request! :)
Don't know if it's nteresting, but I always use this trick so building JSON from DB is so much easier and lighter. :) Good luck.
Here you can check the working code
<?php
$con=mysqli_connect($servername,$username,$password,$databasename);
if (mysqli_connect_errno())
{
echo "Connection Error" . mysqli_connect_error();
}
$query = "SELECT * FROM TableName";
$result = mysqli_query($con,$query);
$querydata = array();
while($data = mysqli_fetch_array($result)) {
$querydata[] = $data;
}
echo json_encode($querydata);
mysqli_close($con);
?>
So i'm trying to pass PDO Query by using php, like this(index.php):
include("dbconn.php");
mysqlConnect("'SELECT * FROM users WHERE name =' . $conn->quote($name))", "jeff");
while my dbconn file that contains the function is(dbconn.php):
function mysqlConnect($queryString, $name) {
// DB Credentials
$dbName = 'db';
$dbUser = 'root';
$dbPass = '';
$dbHost = 'localhost';
try {
$conn = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Here goes the first parameter, then it uses the second parameter as a variable
$data = $conn->query($queryString);
// So the output should be this:
// $data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
foreach($data as $row) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
So in my function call the php actually executes the $conn->quote($name)) code, making my application not work.
How should i do this? is this allowed in php?
Edit:
or in other words: i call a function and give it 2 parameters, one of the parameters(even tho it's in double quotes) is executed by php which shouldn't happen. How can i fix this
The way you wrote, it will never work. You just have to learn to distinguish a string literal from executable code.
Anyways, you don't need such a frankenstein at all. There is already a mechanism to put your variable in the query, called prepared statements. You just have to use them.
There are other issues with your code too. I've described them all in the article I wrote recently, The only proper guide on PDO, I am sure you will find it interesting - all the issues like wrong error handling, utterly wrong way to connect, lack of prepared statements - all described there. Having all of them solved, here goes the proper function you need:
function pdo($sql, $data=[])
{
global $pdo; // you can add a call to your favorite IoC here.
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
return $stmt;
}
used as
include("dbconn.php");
$user = pdo("SELECT * FROM users WHERE name = ?", ["jeff"])->fetch();
var_dump($user);
this is how PDO have to be used.
By returning a statement, you'll be able to use all the power of PDO, getting data you need in one line, say a list
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
var_dump($news); // already an array
or just a single value
$count = pdo("SELECT count(*) FROM posts WHERE author=?", [$id])->fetchColumn();
var_dump($count); // already a number
or simply by iterating results one by one
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
foreach ($news as $row) {
var_dump($row);
}
and so on.
I want to make a data transfer from one database to another using PHP and JSON. The first MySQL connection gets and prints the data (which is working), but the second MySQL connection doesn't insert the data in the 2nd database. I don't know how to execute the INSERT QUERY in order to start filling up the other database(retrieve data from json encode).
This is what I get from the first database:
[{"0":"1","productid":"1","1":"0","parent":"0","2":"","language":"","3":"iPod Shuffle","prodname":"iPod Shuffle","4":"1","prodtype":"1","5":"","prodcode":"","6":"","prodfile":"","7":"
And here is my UPDATED code:
<?php
include 'config/config.php';
//include(dirname(__FILE__) . "/settings.inc.php");
//database 1
$data = array();
$conn = #mysql_connect($GLOBALS['VCS_CFG']["dbServer"],$GLOBALS['VCS_CFG']["dbUser"], $GLOBALS['VCS_CFG']["dbPass"]);
if ($conn){
if (mysql_select_db($GLOBALS['VCS_CFG']["dbDatabase"])) {
$SQL = "SELECT * FROM vc_products";
$q = mysql_query($SQL);
while($row = mysql_fetch_array($q))
{
$json_output[] = $row;
}
echo json_encode($json_output);
$data = json_encode($json_output);
}
mysql_close($conn);
}
// database 2
$con = #mysql_connect($GLOBALS['_DB_SERVER_'],$GLOBALS['_DB_USER_'], $GLOBALS['_DB_PASSWD_']);
if ($con) {
if (mysql_select_db($GLOBALS['_DB_NAME_'])) {
$sql = "INSERT INTO ps_order_detail(product_name) VALUES('".$data[0][8]."')";
$Q = mysql_query($sql);
foreach ($data as $key => $value)
{
$Q -> bind_param(
's', // the types of the data we are about to insert: s = string ( i = int )
$value['prodname']
);
$Q->execute();
}
$Q->close();
}
mysql_close($conn);
}
?>
I don't see you are executing any insert query ¿?
You are just building the string.
A few problems:
You are encoding twice instead of encoding and decoding;
You need to add error handling (PDO and mysqli can throw exceptions, very useful);
You need to get rid of the error supressor operator #;
You should switch to PDO or mysqli and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated.
Not related, but why would you encode and decode to json in the same script when you really want to use the original array?
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}
I have a database table made in phpmyadmin. I want the elements of the table to be stored row-wise in an array. I have three columns named edge_id, vertexA and VertexB. I want the elements of these three columns to be stored into an array.
I don't know those commands for PHP. Please help me out.
i have columns in my table named
"vertexa" and "vertexb",i want to
store the colums in two separate
arrays ...how can i do it??
The simplest way would be:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
$vertices_a = array();
$vertices_b = array();
foreach($db->query('SELECT * from your_table_name') as $row){
$id = $row['edge_id'];
// add them to the proper array using the edge_id as the index -
// this assumes edge_id is unique
$vertices_a[$id] = $row['vertexa'];
$vertices_b[$id] $row['vertexb'];
}
So with PDO:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
foreach($db->query('SELECT * from your_table_name') as $row){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Now if you need to use input data you need to escape it. The best way to do this is to use a prepared statement because escaping is handle when the parameters are bound to the query.
Lets say for example you want to use the edge_id supplied from a get request like mysite.com/show-boundry.php?edge=5...
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
// create a prepared statement
$stmt = $db->prepare('SELECT * from your_table_name WHERE edge_id = ?');
// execute the statement binding the edge_id request parameter to the prepared query
$stmt->execute(array($_GET['edge']));
// loop through the results
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Also you shouldnt use mixed case column/table names like vertexA instead use underscore separators like vertex_a.
You first need to connect to the database:
$link = mysql_connect('localhost','username','password');
if (!$link) {
// Cannot connect
}
$ret = mysql_select_db('database-name', $link);
if (!$ret) {
// Cannot select database
}
Then you need to execute your query:
$ret = mysql_query('SELECT * FROM `table`;', $link);
if (!$ret) {
// Query failed
}
Then you simply load each row:
$data = array();
while ($row = mysql_fetch_assoc($ret)) {
$data[] = $row;
}
Then you should free your request results
mysql_free_result($ret);
And voilà.
$res = mysql_query("............");
$row = mysql_fetch_array($res);
Checkout: mysql_fetch_array PHP page