Creating arrays / json objects, can't quite get this working - php

I have a rather complex situation that I need to get working, for some reason I am almost there but still not quite.
In PHP I create arrays and send to it javascript through json, I am quite sure that my problem is in this part of the code.
$insertIDs = array();
foreach($recipients as $userID)
{
//MySQL insert removed from question
$insertID = mysql_insert_id();
array_push($insertIDs, $array[$userID] = $insertID);
}
$json = array();
$json['fromID'] = $session;
$json['insertIDs'] = $insertIDs;
$json['recipients'] = $recipients;
echo json_encode($json);
when I console.log the results of this in javascript, I get:
{ messageID: 40,
fromID: '1',
insertIDs: [ 44 ],
recipients: [ '3' ] }
Now in javascript when I try to access the insertIDs by the userID which I set it to be in the php above, I just get undefined as a result. How can I do this so I can access each insertID by the userID?
for example: json.insertIDs[userID]
if I simply call it by: json.insertIDs[0] it does return the first insertID, however when there are multiple I need to be able to have an easy way to access each usersID insertID.

I'm not quite sure what you are trying to do, since in the forloop $insertID is always the same value but:
It seems like json.InsertIDs is an array of the form json.InsertIds = Array(44);
Where as you want it to be Array(3 => 44)
try changing your forloop from
foreach($recipients as $userID){
$insertID = mysql_insert_id();
array_push($insertIDs, $array[$userID] = $insertID);
}
to
foreach($recipients as $userID){
$insertID = mysql_insert_id();
$insertIDs[$userID] = $insertID;
}

It seems like the value returned by mysql_insert_id() would be the same every time, unless there was an INSERT query inside that foreach() loop. Is part of the code missing?

Related

Putting data from database into variable using PHP (PDO, MVC)

Today I have looked all over the internet for a good answer. I almost got the answer from this site but that solution didn't work.
Here is what I need to do:
In the database there is a token stored that is going to be used for qr codes. I have already made something to generate the qr code when hardcoded:
$token_qr = "a86ad6352e939eea67da45b8731c3a8d62dcas1r";
$url_qr = some url;
$qr_code = array(
"token" => $token_qr,
"url" => $url_qr
); // end array
$qr_code_encoded = json_encode($qr_code, JSON_UNESCAPED_SLASHES);
$smarty->assign('qr_code_encoded', base64_encode($qr_code_encoded));
The base64 string is put in a url so the qr image can be generated.
Now I need to make it dynamically, the url is always the same but the token is always different. In the model where all the database statements are present I made this:
Class Webservices {
public function GetToken($token) {
$pdo = Database::Get();
$query = "SELECT `site__webservice`.* FROM `site__webservice` WHERE `token` = :token"; // SQL select statement
$params = array(":token" => $token); // bind params
$result = $pdo->Select($query, $params); // run query
// fetch token
if($result) {
$row = PDO::FETCH_ASSOC($result);
return $row[$token];
} else {
return false;
}
}
}
With this function I try to get the token from the database and store this in the $token_qr variable which stand in the controller. To call this I use this:
$webservices = new Webservices();
$token_qr = $webservices->GetToken($token);
The output of this function is now always false. Is there something wrong with my statement or is it in the loop that I created?
Maybe it is something really easy but I can't see the problem and find a solution for it. Thanks in advance for the response!
You need fetch the result before return, use fetch() or fetchAll(). Seems Select() works likes pdo execute() so it's return PDOStatment, fetch it to get the results.
if($result) {
$row = $result->fetchAll(PDO::FETCH_ASSOC);
return $row;

How to generate a JSON objet in PHP with two arrays inside

I´m trying to create my own leaderboards sytem for my games so I´m working with PHP and requesting info with Ajax into the games, but as I´m not good at all with PHP I´m pretty confused about how to create a JSON object with all the info I need to handle in the javascript part.
What I want to do, in the PHP part is to generate this JSON object:
{players: ["name1", "name2", ..., "name10"], scores:[score1, score2, ..., score10]}
So I can work in javascript with something like
dataReceived.players[0]
I´m storing and getting the data correctly from the database but I´m not being able to generate that JSON object to receive in the Ajax request. Basically, this is my PHP code:
$query = "SELECT * FROM leadersboards ORDER by score ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$result_length = mysql_num_rows($result);
$arrayScores = array();
$arrayPlayers = array();
for($i = 0; $i < $result_length; $i++){
$row = mysql_fetch_array($result);
array_push($arrayPlayers, $row['player']);
array_push($arrayScores, $row['score']);
}
$answer = json_encode(array('item' => $arrayPlayers, 'item' => $arrayScores), JSON_FORCE_OBJECT);
Sorry if I made something stupid in PHP, as I said, I don´t know PHP at all, just pretty basic stuff.
The problem is:
array('item' => $arrayPlayers, 'item' => $arrayScores)
You are overwriting the item key right after you set it.
I think you want to do something like this
$answer = json_encode(array('players' => $arrayPlayers, 'scores' => $arrayScores)
Ok, so I fixed it this way, I don´t know if is the best option but it works
$myObject = new stdClass();
$myObject = array(
"players" => $arrayPlayers,
"scores" => $arrayScores,
);
echo json_encode($myObject);
Please stop using mysql_* instead use mysqli_* or PDO.
As per your expected out put of arrays inside object use the below code:
$answer = json_encode(array('players', 'scores'));
$answer->players = $arrayPlayers;
$answer->scores= $arrayScores;

Insert all rows of an array into MySql table - Codeigniter-related

I'm trying to enter 100 email addresses separated by ';' and store them in MySql table. What I've tried so far is:
$recipient_raw = $this->input->post('recipient'); //get the 100 emails in $recipient_raw
$recipient_array=explode(';', $recipient_raw); //explode them into an array
$title = $this->input->post('title');
$body = $this->input->post('body');
foreach($recipient_array->result() as $row):
$recipient=array(
'email'=>$row->email //looping through each email; seems I should not use $row->email since there's no title for them
);
$this->db->insert('eamil_send',$this->db->escape($recipient));
endforeach;
I'm running this on CodeIgniter PHP. Error msg is on line foreach($recipient_array->result() as $row):, where it says: Call to a member function result() on a non-object
Any advice is appreciated! Thanks!
result(), is an active record function for converting a database result object. You are creating a standard array.
$batch = array();
foreach($recipient as $row){
$batch[] = array(
'email' => $row
);
}
$this->db->insert_batch('email_send', $batch);
That should do what you're trying to accomplish.
The error message is pretty much self explanatory..
In the 2nd line of your code you declared $recipient_array as an Array(), not an object. So, there's no "result" method available.
Your loop should be
foreach($recipient_array as $row)
On a side note, you probably shouldn't be executing db operations inside a loop (especially, for 100 operations!). Instead, you should save all the queries in one big query string and execute at the end.
If you want your 100 email address be separate by ',' you should use implode(glue, pieces) instead of explode() function. Like on email address that you want to insert.
$recipient_raw = array();
$recipient_raw[] = $this->input->post('recipient');
foreach ($recipient_raw as $value) {
$tem_arr = implode(',', $value);
}
$this->db->insert('eamil_send',$this->db->escape($tem_arr));

PHP Function is only called once in for loop

I am sure that this question has been asked before, but I am unable to come up with the proper keywords (especially in english).
I am using PHP and I am trying to for loop through a parameter of a function. So the function should be called, store the retrieved data in some variables and these variables should then be inserted into a database.
However, the loops only runs once! If I substitute $id with any number it works fine, but only once.
This is a simplified version of my code:
for ($i=0; $i<9; $i++) {
$id = $rows[$i][1];
$values = getDetails($id); // This function (from another file) returns an array
$title = $values["Title"];
$year = $values["Year"];
$query= " INSERT INTO database
VALUES ('','$title','$year')";
$result = $mysqli->query($query);
}
* EDIT This is part of the getDetails function:
function getDetails($id) {
$url = "http://www.something.de/". $id . "/";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
$title = explode('>',$title[0]);
$title = explode('</span',$title[1]);
... // This might look weird and is definatly not perfect, but it works :)
$details = array("Title" => $title[0], "Year" => $year[1]);
return $details;
}
* EDIT
WOW! I found the reason ... I had a function within my function which was never used. I just commented it out and my code works just fine. I assume it is not a good idea to so anyways.
I think your $query is wrong.
Change this:
$query= " INSERT INTO database
VALUES ('','$title','$year')";
To something like this:
$query= " INSERT INTO database (field1,field2,field3)
VALUES ('','$title','$year')";
Is your ID field autoincrementing? If so you do not need the "field1" entry at all.
Happy Coding!
I had this problem also.
I could print to a table without a problem the parameters I was feeding into a function in a loop. But the function calls in the loops would only call once.
SOLUTION: Remove the location redirects and the exit(); from the function.
Hope this helps someone else.

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

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

Categories