I am trying to sync some polymer element properties with a MySQL database on localhost using MAMP.
How do I pass the SQL data from a PHP variable to a Polymer data binded property?
The Polymer element is as follows:
<iron-ajax id="ajax"
auto
url="../src/data/php/get_data.php"
last-response="{{lastResponse}}"
handle-as="text"></iron-ajax>
...
static get properties() { return {
lastResponse: {
type: Object,
value: {}
}
}}
lastResponse () {
console.log(this.lastResponse);
}
The PHP script is as follows:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
PHP function
get_data.php
should echo(not return) JSON, as:
$res['data'] = 'Hello!';
echo json_encode($res);
and iron-ajax should be set to receive JSON:
handle-as="json"
as in docs here
https://www.webcomponents.org/element/PolymerElements/iron-ajax/elements/iron-ajax
In Polymer first execute the AJAX request, and then receive the data as this:
get_data_responseHandler: function(e) {
console.log(e.detail.response);
}
That is how API point is created.
Related
UPDATE at bottom of question
I'm getting the error:
Warning: mysqli_query() expects parameter 2 to be string, object
given
Questions about this are incredibly common on Stack Overflow - my apologies in advance. I haven't been able to find a good answer for my specific problem. If there is a thread that addresses this, please let me know.
Here is my Ajax code:
$.ajax({
url: "get.php",
type: "post",
datatype: "json",
data:{ ajaxid: altCheck }, //this is an integer passed to MySQL statement
success: function(response){
console.log(response);
},
error: function(){
console.log("test");
}
});
get.php
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
var_dump($value); //checking to see what $value is at this point
$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?");
$sql->bind_param("s",$value);
//THIS LINE THROWS THE ERROR
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
?>
The fourth line of code var_dump($value); outputs string(0).
UPDATE: MySQLi
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
$query = $db->prepare('SELECT * FROM table WHERE screeningId = ?');
$query->bind_param('s', $_GET[$value]);
$query->execute();
if ($result = mysqli_query($db, $query)) {
while ($url = mysqli_fetch_object($result, 'imageURL')) {
echo $url->info()."\n";
}
}
?>
Screenshot of MySQL table data columns:
EDIT
Okay... 8 edits spent on mysqli... Enought!
Here is how I DO using PDO. And it WILL work first shot.
I have a separate file for the database connection info.
dbconnection.php:
(The advantage of the separate definition file is one place to update the user password when needed.)
<?php
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[DATABASE_NAME];host=127.0.0.1';
$user = '[DATABASE_USER]';
$password = '[USER_PASSWORD]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
?>
Now in your PHP files where a database request has to be done, include the PDO definition file, the just request what you want:
<?php
include('dbconnection.php');
// JUST TO DEBUG!!!
$_REQUEST['ajaxid'] = "1";
// Database request.
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
$stmt->bindParam(1, $_REQUEST['ajaxid']);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die;
}
// Looping through the results.
$result_array =[];
while($row=$stmt->fetch()){
array_push($result_array,$row['imageURL']);
}
// The result array json encoded.
echo json_encode($result_array);
?>
Since you are using mysqli_* all other place in your project, update your get.php as below.
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
//var_dump($value); //checking to see what $value is at this point
$sql = "SELECT * FROM table WHERE screeningId = '$value'";
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
EDIT
With respect to bind param with mysqli,
<?php
$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');
$sql = 'SELECT * FROM table WHERE screeningId = ?';
$stmt = $conn->prepare($sql);
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$stmt->bind_param('s', $value);
$stmt->execute();
$res = $stmt->get_result();
$temp = array();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
Select Data With PDO in get.php:
<?php
if( isset($_POST['ajaxid']) ) {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table WHERE screeningId = :screeningId");
$stmt->execute(array(':screeningId' => $_POST['ajaxid']));
$row = $stmt->fetch();
}
?>
You configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $conn object:
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Using one of the tutorials I managed to create a working database retrieval using PHP, JSON and jQuery
Now my question is, if I have multiple query statements that I want to execute what is the best solution?
I have tried opening a second connection in different functions and sending the information as an array in array but that does not work.
database.php:
<?php
function getDbConnection() {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
function home_ratings() {
$db = getDbConnection();
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
$db = null;
return $results_home;
}
?>
get.php:
<?php
require('constant.php');
require('database.php');
$home = home_ratings();
//$top_rest = top_ratings();
//$newr = new_ratings();
//echo json_encode($home);
echo json_encode(array('home' => $home));
?>
info.js:
$( document ).ready(function() {
$.get( "php/get.php")
.done(function(data) {
var results = jQuery.parseJSON(data);
$.each(results, function(i, value) {
//do what i need to do here
})
});
});
You only need one database connection object if you're connecting to the same database in the same method. Instead of having a function for getDbConnection() instead make the $db variable global and use it within functions (you may need to put a line global $db; in the function to ensure that it can access the global variable).
Example of how your database.php file could look:
<?php
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function home_ratings() {
global $db; // $db scope of global
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
return $results_home;
}
?>
I am trying to fill a dropdown list from a mysql database by using ajax and jquery. The data is should be in json format. But I keep getting syntax error: JSON.parse: unexpected character. Please advise. Thank you for your help.
This is my code in Dreamweaver
$(document).ready(function(){
$.getJSON("http://localhost:8000/states.php", function(data) {
$.each(jsondata, function(index, item) {
$('<option></option>').val(item.state_code).html(item.state).appendTo("select#personalstate");
});
});
});
Database code:
database.php
<?php
$dsn = 'mysql:host=localhost;dbname=elihu';
$username = 'admin';
$password = 'password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$db = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
?>
json php file
<?php
require('database.php');
function getStates() {
global $db;
$query = 'SELECT * FROM states';
try {
$statement = $db->prepare($query);
$statement->execute();
$states = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
echo json_encode($states);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
}
?>
$.getJSON("Model/php/states.php", function(data) {
// No need to parse the json data, it's already been parsed by getJSON
// jsondata = $.parseJSON(data);
i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>
i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.