I don't know what is the problem.
I have this part of my php:
public function fillObject(){
try {
$servername = "localhost";
$username = "root";
$password = "123asd";
$conn = new PDO("mysql:host=$servername;dbname=bd_actividades", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT pro_nombre FROM act_proyecto");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
foreach ($result as $row) {
$aObjects=array();
$oTransfer = new TransferProyeCtr();
$oTransfer->setNombre($row['pro_nombre']);
$oTransfer->setState(1);
$aObjects[]=$oTransfer;
return $aObjects;
} }catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
} }
this send the results : $oTransfer->setNombre($row['pro_nombre']);
And in my dropdown show this:
But I need this :
What is the problem?
Here is my module where I print:
Ajax:
llenarComboProyectos: function(iSecciones){
var self = this;
self.ajaxCall('http://localhost:8080/PROJECTS/dailytasks/api/sistemaTareas/v1/'+"proyectos","GET", null).then(function(data) {
console.info("data",data);
if(self.checkError(data[0].state)){
self.llenarCombos(iSecciones,data);
}else{
alert("error service");
}
});
},
Where I print:
llenarCombos: function(secciones,data){
var self = this;
console.info(data);
for (var i = 0; i < data.length; i++){
var cProyectos = "<option>"+data[i].nombre_proyecto+"</option>";
for(var iCont=0;secciones>=iCont; iCont++){
$("#select_proyecto_"+iCont+"_id").append(cProyectos);
$("#select_proyecto_"+iCont+"_id").selectpicker('refresh');
}
}
},
here I get pro_nombre: var cProyectos = "<option>"+data[i].nombre_proyecto+"</option>";
Please remove
$stmt->setFetchMode(PDO::FETCH_ASSOC);
from your first script.
I think this will solve your problem.
http://php.net/manual/en/pdostatement.fetch.php
http://php.net/manual/en/pdostatement.fetchall.php
Related
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.
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);
I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;
I'm playing with jQuery's $.ajax and I'm not sure how I should be doing the following:
Here's my javascript (right now its just embedded in the html page)
$.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {
console.dir(data);
},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
Here is what DBConnect.php looks like:
$username = "root";
$pass = "pass";
$host = "127.0.0.1";
$dbname = "test";
//queries
$table = "events";
$fetchAll = "SELECT * FROM $table";
try {
$DB = new PDO("mysql:host=$host;dbname=$dbname", $username, $pass);
//_WARNING uncommented when debugging
$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
//$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = $DB->query($fetchAll);
$query->setFetchMode(PDO::FETCH_OBJ);
while($row = $query->fetch()) {
echo json_encode($row);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
$DB = null;
Doing this I get a syntax error. I thought I could get away with returning every row as a json object, but clearly that doesn't work. I could just add all the row objects to one array and convert that to json, but I wanted to know if there was a better\more efficient way to do this.
Change the while loop:
$temp = array();
while($row = $query->fetch()) {
$temp[] = $row;
}
echo json_encode($temp);
Try this, and let me know if that helps!
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);