I cannot get valid data from the Zend Framework sql statements shown below which I use in php and is called from an angularjs script:
$where = new Where ();
$where->greaterThanOrEqualTo('user_id', '963');
$resultSet = $this->tableGateway->select(function(Select $select) use
($where){
$select->where($where);
$select->columns(array('date_added','datemonth' => new \Zend\Db\Sql\Expression("MONTH('date_added')"), 'count' => new \Zend\Db\Sql\Expression("COUNT(*)")));
$select->group('datemonth');
return $resultSet;
My angular js script dumps the data as shown below:
success(function(response) {
for(var i in response.response) {
var tc = response.response[i];
alert("userdata date_added=" + tc['date_added'] + " datemonth=" + tc['datemonth'] + " count=" + tc["count"]);
}
And the results are as shown:
userdata date_added=2014-05-22 20:00:27 datemonth=undefined count=undefined
Can anyone tell me if I am using the Zend\Db\Sql\Expression incorrectly or why isn't the datemonth and count not coming back correctly? I want to be able to get the number of records by month.
Update: I was able to dump the putput from the server and it shows all the fields on the database record but none for the fields created in the Zend Expression functions for datemonth and count. Below is the dump. Anyone know why the Expression fields aren't in the dump?
Php Code:
echo "Resultset = " . $resultSet->date_added;
Dump of above code:
Resultset = {"success":true,"response":[{"inputFilter":null,"user_id":0,"instagram_user_id":"","fbid":"","instagram_username":null, "full_name":"","profile_image":"","bio":"","website":"","media_count":0,"following_count":0,"followed_by_count":0,"like_count":0,"recommend_count":0,"date_added":"2014-05-22 20:00:27","flag_count":0,"date_updated":"","email":"","password":"","access_token":"","premium":0,"login_attempts":0,"status":0,"request_count":0,"request_date":""}]}
You may try this to preview your SQL query:
$sql = new \Zend\Db\Sql\Sql($this->tableGateway->adapter);
echo $sql->getSqlStringForSqlObject($select);
Related
I am building a web application and there is a part there where I need to load records from a store given a set of ids. The way I went about this was to get all the ids, store them in an array, and then load the store with that array as an extra param.
Here is my code:
for(var i = 0 ; i < store.count() ; i++){
console.log("id person = " + store.getAt(i).get("ID_PERSON"));
idArray.push(store.getAt(i).get("ID_PERSON"));
}
console.log("id array = " + idArray);
store = Ext.getStore('borrowerListStore');
store.getProxy().extraParams={
idArray: idArray
};
store.load({
callback: function(records, operation, success) {
var total = operation.request.scope.reader.jsonData['total'];
var message = operation.request.scope.reader.jsonData['message'];
console.log("message = " + message);
}
});
First, I go though my initial store then get all the ids and store them in an Array. After that, I declare my store, I get the proxy, I set the params, and then I use the idArray I assembled as the array.
The console line shows me proper values for example 77, 24, 80 so I know that I passed 3 values.
Then in my PHP code linked in the read method of my store, I do this:
else if(isset($_GET['idArray'])){
$idArray = $_GET['idArray'];
$array = $idArray;
for($i = 0 ; $i < count($idArray) ; $i++){
array_push($array, $idArray[$i]);
}
$sql = "SELECT * FROM TABLE WHERE ID IN(".implode(',',$array).")";
$result = mysql_query($sql);
$res->message .= " Loaded data ";
$res->message .= " sql = " . $sql;
$res->message .= " idArray = " . $idArray;
$res->message .= " array = " . $array;
$total = mysql_fetch_array($totalquery);
}
So that when the store loads and I enter the callback function, I can see the messages that got returned.
However, when I console out the messages, it seems to me that only the last array element is the only thing that my PHP received because the log would look like:
message = Message start Loaded data sql = SELECT * FROM TABLE WHERE ID IN() idArray = 80 array = 80
What's happening here? Why can't I seem to pass an array as extra param?
First of all, I am not sure whether you really want to transmit arrays as GET parameters. If the arrays become bigger, you run into max URL length issues. I would definitely recommend to use POST and transmit JSON to the server.
ExtJS 4.2.2 sends the array to the server correctly, I have checked in a fiddle that this cannot be the issue.
But I am not sure whether PHP understands the format in which it is sent. It seems as if when I call test.php?x=1&x=2, $_GET['x'] is not an array [1,2], but only a number 2. I am not sure why, though, I have not looked into PHP code. As a quick hack you could use
store.getProxy().extraParams={
idArray: idArray.join(',')
};
on the client side to transmit the ids as a string instead of array, and decode that string back into ids with
$array = array_map("intval",explode(",",$_GET['idArray']));
on the server side. (If you don't use intval and use the string without any check in the SQL query, you are prone to SQL injection attacks.)
hey try to change this line
array_push($array, $idArray[$i]);
to
$array[] = $idArray[$i];
I am getting an error when trying to pass a variable from AJAX to PHP for a MySQL query. I have tried hardcoding to make sure that the query works and it does, but when I try to dynamically pass the variable it is telling me the following "Error: Unknown column '$searchid' in 'where clause'". I am trying to send the value of a dropdown box to ajax to pull back data from a MySQL database. The returned data will then be put into 2 text boxes to be edited. Note: I am trying not to use the jQuery framework for this so I can get a better understanding of what the AJAX is actually doing.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
It's been a while since I have had time to work with code so I believe everything I used is still relevant. Also I know I havent put any sanitizing in yet, I wanted to make sure I can get the function working first, and I am the only one with access currently.
Thanks in advance for any help.
To solve your immediate issue, you'll want to change this:
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
Into this:
$sql = "SELECT * FROM orginfo WHERE id = $searchid";
Since your string is in single quotes, it is literally passing the string '$searchid' into the query rather than the value of $searchid.
I'm a complete novice, and have been asked to finish a project for someone (much more knowledgeable than I) who has just left.
I currently have a MySQL database, which I am trying to export as an XML file. This is going fine, but unlike PHP, I can't combine two separate columns.
So where I have two entries - lat (latitude), and Lon (longitude) - in my MySQL database, I can't output them in XML as one entry.
In PHP I would simply write: $latlon = $lat.",".$lon;
But I cannot do so in the XML output below.
Does anyone know how I could write this to achieve the required result, of simply having two entries listed under one child?
function createxml($x) {
global $mysqli;
include('xml.php');
$sxe = new SimpleXMLElement($xmlstr);
//get mysql data
if ($result = $mysqli->query("SELECT id,county,main_page,lat,lon,volume,texty,pdf,thumb FROM texts3 ORDER BY id ASC LIMIT $x"))
{
//found volumes already in DB
while ($r = $result->fetch_array(MYSQLI_BOTH)) {
$record = $sxe->addChild('record');
$record->addChild('latitude', $r['lat']);
$record->addChild('longitude', $r['lon']);
$record->addChild('latlon', $r['']);
}
$result->close();
}
If you have the r array why don't you try:
while ($r = $result->fetch_array(MYSQLI_BOTH)) {
$record = $sxe->addChild('record');
$latlon = $r['lat'].",".$r['lon'];
$record->addChild('latitude', $r['lat']);
$record->addChild('longitude', $r['lon']);
$record->addChild('latlon', $latlon);
}
Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all
I'm trying to use a MERGE INTO statement in my php file to update or insert into a MySQL database for a multiplayer game.
Here's a full description of what I'm trying to accomplish:
The php file is called with the following line from a javascript file:
xmlhttp.open('GET', "phpsqlajax_genxml.php?" + "lat=" + lla[0] + "&heading=" + truckHeading + "&lng=" + lla[1] + "&velocity0=" + vel0 + "&velocity1=" + vel1 + "&velocity2=" + vel2 + "&id=" + playerNumber, true);
This will be sending the php file information to update the database with. Either this will be a new player and the first time this information has been sent, meaning that a new row in the database will be created, or it will be a current player who just needs to have their information updated.
If it is a new player the "id" that is sent will be one that doesn't yet exist in the database.
For some reason the database isn't being updated, nor are new rows being added. I'm thinking it's a syntax error because I don't have much experience using MERGE statements. Could someone with experience with this please let me know what I might be doing wrong?
Here is the code before the MERGE INTO statement so you can understand which variables are which:
$id = $_GET['id'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$heading = $_GET['heading'];
$velocity0 = $_GET['velocity0'];
$velocity1 = $_GET['velocity1'];
$velocity2 = $_GET['velocity2'];
id is the column heading, $id is the id being passed in
Here is my current MERGE INTO statement in my php file:
MERGE INTO markers USING id ON (id = $id)
WHEN MATCHED THEN
UPDATE SET lat = $lat, lng = $lng, heading = $heading, velocityX = $velocity0, velocityY = $velocity1, velocityZ = $velocity2
WHEN NOT MATCHED THEN
INSERT (id, name, address, lat, lng, type, heading, velocityX, velocityY, velocityZ) VALUES ($id, 'bob', 'Poop Lane', $lat, $lng, 'Poop', $heading, $velocity0, $velocity1, $velocity2)
PHP's database libraries invariably have their various function calls return FALSE if anything failed during the call. Assuming you're on mysql_/mysqli_, then you shoudl be doing something like this:
$sql = "MERGE INTO ....";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
It is poor practice to NOT check the return values from database calls. Even if the query string is 100% syntactically valid, there's far too many ways for a query to fail. Assuming everything works is the easiest way to get yourself into a very bad situation. As well, when things do fail, the lack of error handling will simply hide the actual reason for the error and then you end up on SO getting answers like this.
Oh, and before I forget... MySQL doesn't support "MERGE INTO...", so your whole query is a syntax error. Look into using "REPLACE INTO..." or "INSERT ... ON DUPLICATE KEY UPDATE ..." instead.