I have a SQLite query in PHP:
$database = new SQLite3("database.db");
$statement = $database->prepare("SELECT * FROM table");
$result = $statement->execute();
$table = array();
while ($row = $result->fetchArray()) {
array_push($table, $row);
}
var_dump($table);
and it outputs
array(2) {
[0]=> array(4) {
[0]=> int(1)
["event"]=> int(1)
[1]=> string(2) "A1"
["code"]=> string(2) "A1"
}
[1]=> array(4) {
[0]=> int(5)
["event"]=> int(5)
[1]=> string(2) "A2"
["code"]=> string(2) "A2"
}
}
Which is the correct data, but it's outputting all of the information twice: one with an index attached, and one with the column name. Is there any way to pick one or the other? This program needs to be very memory efficient as it will be expanded to having thousands of rows.
This will give you a regular mysql-style assoc array output,
$db = new SQLite3('dbs');
$result = $db->query("SELECT * FROM table");
$assoc_array = array();
while ($dbs_row = $result->fetchArray(SQLITE3_ASSOC)) {
$assoc_array[] = $dbs_row;
}
SQLite's fetchArray function can take a mode parameter. You can use SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH for the desired effect. I guess I should've looked at the documentation before I posted :)
Related
When I encode the json data fetching from the mysql database, I get this:
[{"userid":"11","postid":"12"},{"userid":"13","postid":"12"},{"userid":"16","postid":"12"}]
And I am trying to get only the userid's like this: 11, 13, 16.
Decoding the json data gives me an output of: Array. And nothing else. When I var_dump this is my results:
array(3) {
[0]=> array(2) {
["userid"]=> string(2) "11"
["postid"]=> string(2) "12"
}
[1]=> array(2) {
["userid"]=> string(2) "13"
["postid"]=> string(2) "12"
}
[2]=> array(2) {
["userid"]=> string(2) "16"
["postid"]=> string(2) "12"
}
So I know there is data present, it's just not showing for some reason.
Here is what my query looks like:
if(isset($_POST['postuserid'])){
$uid = $_POST['postuserid'];
$ssql = "SELECT * FROM foodid WHERE postid=$uid";
$rresult = mysqli_query($db,$ssql);
while ($lrow = mysqli_fetch_assoc($rresult)){
$ret[] = $lrow;
$postjson = json_encode($ret);
$decode_postid = json_decode($postjson, true);
$new_postid = $decode_postid;
}
var_dump($new_postid);
die($new_postid);
// die($new_postid['userid']); is what I need along with all data userid fetched.
}
Is there a reason why this works when I encode json data, but not when I decode the json data?
Are you trying to get that array out of the die function? It can only take a string or int.
http://php.net/manual/en/function.exit.php
Your array is there... just do something like:
$ids = '';
foreach ($new_postid as $post) {
$ids .= $post['userid'] . ',';
}
$ids = rtrim($ids,',');
die($ids);
Try mapping those results:
$new_postid = $decode_postid;
$new_postid = array_map(function($item){
return $item['userid'];
}, $new_postid);
var_dump($new_postid);
Output
array(3) {
[0]=>
string(2) "11"
1=>
string(2) "13"
[2]=>
string(2) "16"
}
If you need to output as string, just use implode function
die(implode(',',$new_postid));
http://php.net/manual/en/function.array-map.php
The following code gives the array below, however I need it formatted differently (stated after the array), so it will work for a javascript function I've already written.
$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC";
$result = mysqli_query($conn, $sql);
$dbarray = array();
while($row = mysqli_fetch_assoc($result)) {
$dbarray[] = $row;
}
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
0 => $values['amount'],
1 => $values['towhich']
);
$cnt ++;
}
//Now it's grouped by date
Array output:
array(5)
{
["02"]=> array(2)
{
[0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
[1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" }
}
["03"]=> array(1)
{
[2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" }
}
["04"]=> array(1)
{
[3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" }
}
["05"]=> array(2)
{
[4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" }
[5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
["06"]=> array(1)
{
[6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
}
The key index value for array should not be, for example, ['02'], but, being the first in the containing array, [0], like normal; and '03' should be [1].
I've looked around a lot, indeed it helped with what bit of code I've produced, however all answers seem to deal with changing the key value further inside the large array. I'm new with multidimensional arrays, btw. Thanks in advance.
In case you're wondering why I've done it like so, so far, it's because each first array should correspond to a different month; that's why I've ordered by date and all that.
If I got you right, you can use: array_values :
$graph = array_values($graph);
so "02" will be 0, "03" will be 1 , ... etc.
$key in your foreach will be the relative record number that the row occurs in the query.
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
$graph[$key] = array (
$month,
$values['amount'],
$values['towhich']
);
$cnt ++;
}
I've been trying to create an array from a mysqli query that creates a new class 'Book'. When I run this code, it returns the correct number of rows that I have in my database, but it won't display any of the values in the rows. Definitely a newb to a lot of this stuff, any help is really appreciated! Here's the code I'm running. If I just put in a pre-populated array, the code all works great. My problem is getting the values from the database into this array.
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$thearray[] = array(
$array_ar['username'] => new Book($array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
}
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
Ok, so I var_dump($thearray); and it gives me a multidimensional array, which is why it's returning empty values. I think I need it to return an associative array? Here's what it var_dump($thearray); returns:
array(4) {
[0]=> array(1) {
["joshua"]=> object(Book)#6 (3) {
["title"]=> string(6) "joshua" ["author"]=> string(6) "Joshua" ["description"]=> string(9) "Lundquist"
}
}
[1]=> array(1) {
["matthew"]=> object(Book)#7 (3) {
["title"]=> string(7) "matthew" ["author"]=> string(4) "Matt" ["description"]=> string(3) "Alm"
}
}
[2]=> array(1) {
["roger"]=> object(Book)#8 (3) {
["title"]=> string(5) "roger" ["author"]=> string(5) "Roger" ["description"]=> string(9) "Lundquist"
}
}
[3]=> array(1) {
["norm"]=> object(Book)#9 (3) {
["title"]=> string(4) "norm" ["author"]=> string(4) "Norm" ["description"]=> string(5) "Shupe"
}
}
}
Next I thought I would take a look at what the var_dump(); for my hard-coded array looks like, and it output this (this one works):
array(3) {
["Jungle Book"]=> object(Book)#3 (3) {
["title"]=> string(11) "Jungle Book" ["author"]=> string(10) "R. Kipling" ["description"]=> string(15) "A classic book."
}
["Moonwalker"]=> object(Book)#4 (3) {
["title"]=> string(10) "Moonwalker" ["author"]=> string(9) "J. Walker" ["description"]=> string(7) "another"
}
["PHP for Dummies"]=> object(Book)#5 (3) {
["title"]=> string(15) "PHP for Dummies" ["author"]=> string(14) "Some Smart Guy" ["description"]=> string(18) "and the final one."
}
}
It makes sense to me what's happening, but I'm not sure how to fix my code. Thank you for the help!
Don't Panic's answer got me looking in the right direction. I needed to create an associative array, not a multidimensional array. At first I was accidentally creating the multidimensional array by setting $thearray equal to "array();". By removing that, it filled in the values correctly. Thanks again for the help!
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$title = $array_ar['username'];
$author = $array_ar['username'];
$description = $array_ar['username'];
$thearray[] = $title = new Book($title, $author, $description);
}
var_dump($thearray);
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
I think this is the problem.
$thearray[] = array(
$array_ar['username'] => new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
It looks like the differences between what you're getting and what you want is 1) You're wrapping the input to $thearray in an extra array() layer, and 2) You won't get string keys like you have in your hard-coded array if you just add the items using [].
Try it like this instead:
// use the username as a key, since that is what it looks like you're using as the 'title'
$thearray[$array_ar['username']] = new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']);
I am trying to execute an SQL query to pull one column of data from my database into a PHP array, and then search for my session variable in that array. I've printed the contents of my array and it looks like the query is working and is filling the array, but my comparison if (in_array("$session", $result)) is not working correctly.
I know the string my session variable contains is inside the PHP array. But $execute never flips to FALSE. Any idea why?
$confirm = $_GET['name'];
$execute = TRUE;
session_start();
$session = $_SESSION['sessionID'];
$result = array();
try{
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(substr($session, 0, 2) === 'DS'){
$sql = $conn->prepare("SELECT confirmNum FROM `DSattendance`");
$sql->execute();
$result = $sql->fetchAll();
}
else if (substr($session, 0, 2) === 'BYOD'){
$sql = $conn->prepare("SELECT confirmNum FROM BYODattendance");
$sql->execute();
$result = $sql->fetchAll();
}
}
catch(PDOException $e){echo $sql . "<br>" . $e->getMessage();}
if (in_array("$session", $result)) {
echo "true";
$execute = FALSE;
}
if ($execute == FALSE)
echo "ALREADY REGISTERED";
var_dump($result) yields:
array(10) {
[0]=> array(2) { ["confirmNum"]=> string(11) "adfafafafaa" [0]=> string(11) "adfafafafaa" }
[1]=> array(2) { ["confirmNum"]=> string(11) "adsfafafaff" [0]=> string(11) "adsfafafaff" }
[2]=> array(2) { ["confirmNum"]=> string(11) "asdfafafafa" [0]=> string(11) "asdfafafafa" }
[3]=> array(2) { ["confirmNum"]=> string(11) "christrader" [0]=> string(11) "christrader" }
[4]=> array(2) { ["confirmNum"]=> string(11) "christradfe" [0]=> string(11) "christradfe" }
[5]=> array(2) { ["confirmNum"]=> string(11) "sadfadfafaf" [0]=> string(11) "sadfadfafaf" }
[6]=> array(2) { ["confirmNum"]=> string(11) "sadfsfafaaf" [0]=> string(11) "sadfsfafaaf" }
[7]=> array(2) { ["confirmNum"]=> string(11) "sdfsafsadfa" [0]=> string(11) "sdfsafsadfa" }
[8]=> array(2) { ["confirmNum"]=> string(11) "trraafafafa" [0]=> string(11) "trraafafafa" }
[9]=> array(2) { ["confirmNum"]=> string(11) "wesdfdfasfa" [0]=> string(11) "wesdfdfasfa" } }
The PDO Statement fetchAll is returning a multi-dimensional array of the results found in the database. You need to loop through them first and format a new array that you can use to check your session against.
foreach($result as $value) {
$array[] = $value['confirmNum'];
}
if( in_array($session, $array)) {
// your code here
}
As noted by #mr12086, depending on the version of PHP you are using, you can avoid the foreach loop by using: $result = array_column('confirmNum', $result); instead. However, this does require PHP 5.5.0 or higher.
$sql = "SELECT catgy.category_id, catgy.category_title
FROM categories catgy
INNER JOIN subj_category_relation scr
ON scr.scr_id = catgy.category_id
INNER JOIN subjects subj
ON subj.subject_id = '{$sId}'
WHERE subj.subject_id = '{$sId}'
AND subj.subject_id = scr.subject_id";
$res = $this->db->query( $sql );
if ($res) {
$results = $res->result_array();
echo "<pre>";
var_dump( $results );
echo "</pre>"
exit;
vardump
array(5) {
[0]=>
array(2) {
["category_id"]=>
string(1) "1"
["category_title"]=>
string(5) "terms"
}
[1]=>
array(2) {
["category_id"]=>
string(1) "2"
["category_title"]=>
string(6) "people"
}
[2]=>
array(2) {
["category_id"]=>
string(1) "3"
["category_title"]=>
string(8) "places
"
}
[3]=>
array(2) {
["category_id"]=>
string(1) "4"
["category_title"]=>
string(7) "works
"
}
[4]=>
array(2) {
["category_id"]=>
string(1) "5"
["category_title"]=>
string(8) "events
"
}
}
Getting Database int type in string. What is the proper solution? Instead converting each array may be not good solution.
Database object should return correct value type in object. there is issue in PHP/MySQL older versions.
https://dev.mysql.com/downloads/connector/php-mysqlnd/
Install php5-mysqlnd driver
apt-get install php5-mysqlnd
service apache2 restart
Reference:
MySQL integer field is returned as string in PHP
Check #advait answer
$new_int_array = array();
foreach($results as $value){
$new_int_array [] = array_map('intval', $value);
}
print_r($new_int_array); //this is new array with int type values.
Try array_walk to convert string to int:
array_walk($results, function(&$a) {
$a['category_id'] = (int)$a['category_id'];
});
var_dump($results);
DEMO
When retrieving even integers from DB it is converted to string so you have to manually convert them back to int