I'm trying to make a new column with results from an SQL query in PHP:
$someArray= array(array('match'=>'123'), array('match'=>'456'), array('match'=>'789')); //arbitrary number of elements
foreach($someArray as $key=>$item){
$someArraysDouble[]=$item;
}
$someQuery="select count(*) as somecount from sometable";
$probe1=array();
$probe2="0";
$probe3="0";
$probe4="0";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";//myDB uses MySQL
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($someArray as $key=>$item) {
$someQuery.=" where somecolumn like "%$item['match']%";
$blahblah=$conn->query($someQuery);
if ($blahblah->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['match']=$item['match'];
$probe1[]=$row;
}
}
$conn->close();
}
foreach($someArraysDouble as $key1=>$item1) {
foreach($probe1 as $key2=>$item2) {
if($item2['match']==$item1['match']) {
$probe2=$item1['somecount'];
$probe3=$item2['somecount'];
$item1['somecount']=$item2['somecount'];
$probe4=$item1['somecount'];
}
}
}
The output HTML looks like this:
<html>
<head></head>
<body>
{$probe2}<br>{$probe3}<br>{$probe4}<br><br>
{loop $probe1 $key1 $item1}
{$item1['somecount']}<br><br>
{/loop}
<br><br>
{loop $someArraysDouble $key2 $item2}
{$item2['somecount']}<br><br>
{/loop}
</body>
</html>
Result is... something I don't understand:
- $probe2 is null, which is expected.
- $probe3 is the count value for last element, which is expected.
- $probe4 is the count value for last element, which is expected.
- The first loop with $probe1 produces the count value for each element, which is expected.
- The second loop with $someArraysDouble produces nothing, which is NOT expected. HOW can this happen?
For some reason that I'm not sharing in order to keep this question concise, I need to have the count value for each element outputted via $someArraysDouble.
I suspect that this line is not performing as you expect because you have not created $someArraysDouble before entering the loop:
$someArraysDouble[]=$item;
Try creating an empty array first, like this:
$someArraysDouble = array(); // <== Initialize the array first
$someArray = array(array('match'=>'123'), array('match'=>'456'),
array('match'=>'789')); //arbitrary number of elements
foreach($someArray as $key=>$item){
$someArraysDouble[] = $item;
}
See the PHP Array docs for more info, specifically the section "Creating/modifying with square bracket syntax".
Turns out it was me not understanding how foreach in PHP works.
function array_generate(){
return array(array('match'=>'123'), array('match'=>'456'), array('match'=>'789')); //arbitrary number of elements
}
$someArray=array_generate();
var_dump($someArray);
foreach($someArray as $heavy=>$load)
{
$load['addedvalue']="newvalue";
$test1[$heavy]="newvalue";
$test2[$heavy]=$load['addedvalue'];
var_dump($someArray);
}
var_dump($someArray);
var_dump($test2);
The n+2 var_dump($someArray)s (where n==count($someArray)) all show the same.
array(3) { [0]=> array(1) { ["match"]=> string(3) "123" } [1]=> array(1) { ["match"]=> string(3) "456" } [2]=> array(1) { ["match"]=> string(3) "789" } }
But var_dump($test2) shows:
array(3) { [0]=> string(8) "newvalue" [1]=> string(8) "newvalue" [2]=> string(8) "newvalue" }
This means the addedvalue of each element of $someArray does not persist once $key changes. So my solution is to use a new array, which is synced with the original array, length-wise.
Related
I am working PHP and MySQL. I am created a database and table. I want to convert table to JSON. So, I write this code block:
<?php
include "../config/database.php";
$SQLUser = "SELECT * FROM tbl_user";
$SQLUserResult =mysqli_query($Conn,$SQLUser );
$JSON= array();
while($row=mysqli_fetch_assoc($SQLUserResult ))
{
$JSON[] = $row;
}
$Show = json_encode($JSON);
echo count($JSON);
echo $Show;
?>
When run this page, I take JSON size correctly. But I can't display JSON values. What can I do?
In the page source, I see the count of rows in my JSON array (13), but no data.
Adding var_dump($row); shows me something like
array(13) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(1) "A" ["surname"]=> string(1) "A" } [1]=> array(3) { ...
The encoding is utf8_general_ci.
I think, your database or tables returns probably a faulty response, some strings were probably not UTF-8. So, You can create a function for convert UTF-8.
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
Than, you can encode just like this:
echo json_encode(utf8ize($JSON));
The problem is easy. The answer is not
I have an array with multiple (2) dimensions.
The code is easy (line 28-32):
<?php
foreach($select_all_data as $key => $value) {
foreach ($value as $v => $k) {
$all_values = $v.",";
}
}
?>
But when I excecute it, it shows me
Warning: Invalid argument supplied for foreach() in D:\xampp\htdocs\qlb\test.php on line 29
(I also tested $value al array with is_array, that gave me true)
An example output of $value in the loop is:
array(12) {
["id"]=>
string(3) "101"
["aangever_voornaam"]=>
string(8) "censored"
["aangever_achternaam"]=>
string(6) "censored"
["aangever_geslacht"]=>
string(3) "Male"
["pleegplaats"]=>
string(6) "censored"
["pleegdatum"]=>
string(10) "dd-mm-yyyy"
["pleegtijd"]=>
string(5) "hh:mm"
["verbalisant"]=>
string(12) "censored"
["verklaring"]=>
string(229) "censored"
["opnamedatum"]=>
string(19) "yyyy-mm-dd hh:mm:ss"
["status"]=>
string(4) "open"
["behandelaar"]=>
string(12) "censored"
}
As you can see, its a nice array that I want to put in the loop. But it gives me the invalid argument error.
What did I do wrong?
For the record: I tried to create a script to export a whole database with this script
<?php
$DB_HOST = "";
$DB_USER = "";
$DB_PASS = "";
$DB_NAME = "";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$select_all_tables = array();
$select_all_data = array();
$show_tables_from = $con->query("SHOW TABLES FROM `$DB_NAME`");
while ($row = $show_tables_from->fetch_assoc()) {
$select_all_tables[] = $row['Tables_in_'.$DB_NAME.''];
}
foreach ($select_all_tables as $a) {
$q = $con->query("SHOW CREATE TABLE `$a`");
$show_create_table[] = $q->fetch_assoc()['Create Table'];
$q = $con->query("SELECT * FROM `$a`");
$select_all_data[] = $q->fetch_assoc();
}
echo "<pre>";
//var_dump($a);
//var_dump($show_create_table);
//var_dump($select_all_data);
foreach($select_all_data as $key => $value) {
var_dump($value);
}
?>
Acording to fetch_assoc docs
Returns an associative array that corresponds to the fetched row or
NULL if there are no more rows.
So for those $value elements inside the loop that end up being null you will have that error thrown..
So just wrap it in if statement like:
if (!is_null($value)) {
foreach ($value as $v => $k) {
$all_values = $v.",";
}
}
or maybe even is_array($value) to make sure you able to iterate thru...
The arrays had a diffrent number of keys. I think because I forgot to loop the query in the first foreach (after the while)
So I changed that to
foreach ($select_all_tables as $a) {
$q = $con->query("SHOW CREATE TABLE `$a`");
$show_create_table[] = $q->fetch_assoc()['Create Table'];
$q = $con->query("SELECT * FROM `$a`");
while ($row = $q->fetch_assoc()) {
$select_all_data[] = $row;
}
}
And that was the solution!
I have the following problem:
I'm iterating through an array of valid objects using foreach. When trying to access the resulting objects or their properties I am getting the notice I would be trying to access a non-object.
Here is the code:
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
if ($node->status == 1) {
$data = $node->id;
}
}
var_dump outputs the following:
object(stdClass)#5 (6) {
["status"]=>
int(0)
["id"]=>
int(1)
["title"]=>
string(6) "Sensor"
["script"]=>
string(24) "from eZness import swag;"
["x"]=>
int(60)
["y"]=>
int(80)
}
Thanks in advance.
UPDATE:
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
echo $node->status; //Funnily this works
$status = $node->status; //while this doesn't
if ($node->status == 1) { //and this doesn't as well
$data = $node->id;
}
}
But when removing the var_dump even the echo doesn't work anymore.
UPDATE:
Resolved. Had a look at the client part of the application, there was a problem with pushing NULL values in the $schema->node array which of course are non-objects.
You are trying to access $node->data, which does not exist.
Perhaps more of a workaround than an answer but: use
$schema = json_decode($_POST['d'],true);
When you pass true as the second parameter, you get back an associative array instead of an object.
You should be able to loop through it with this:
$schema = json_decode($_POST['d'],true);
foreach ($schema['node'] as $node) {
if ($node['status'] == 1) {
$data = $node['id'];
}
}
this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)
Basically, i'm trying to get users data from a database using a class i found, it's parsing all data inside an array as shown here from the following function :
public function Get($field = NULL) {
if ($field == NULL)
{
$data = array();
while ($row = mysql_fetch_array($this->last_query))
{
$data[] = $row;
}
}
else
{
$row = mysql_fetch_array($this->last_query);
$data = $row[$field];
}
return $data;
}
Here's the PHP code i'm using to get the call this function
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_SESSION['csrfToken'] == $_POST['csrfToken']) {
$email = $_POST['email'];
$password = $Security->Salt($Security->secParam($_POST['password']));
$DB->Query("SELECT * FROM `table` WHERE `email` = '$email' AND `password` = '$password'");
if($DB->num_rows() > 0) {
$results = $DB->Get();
} else {
echo "Account not found";
}
}
}
If i do a var_dump on $results it shows the following
array(1) {
[0]=> array(8) {
[0]=> string(1) "1" ["id"]=> string(1) "1"
[1]=> string(35) "email#email.com" ["email"]=> string(35) "email#email.com"
[2]=> string(32) "4f14dfef1efe0de64e2b176eac6051cd" ["password"]=> string(32) "4f14dfef1efe0de64e2b176eac6051cd"
[3]=> string(1) "1" ["status"]=> string(1) "1"
}
}
how can i access this data ? I've tried calling it by doing the following
$email = $results['email'];
echo $email;
But it's not displaying anything ?
Even though there's only one result in this instance (I guess?) the array supports multiple.
So find the first result, then take the email from that:
echo $results[0]['email'];
// ^^^^^^^^^^^
// first result
You need to tracking how arrays works. First you have array(1) and then into array another vars such as "email" or 1.
array(1) { <---- THIS IS ARRAY OCCURED FOR FIRST "0" ARRAY.
What's about
this
\/
echo $results[0]["email"]; ?
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['csrfToken'] == $_POST['csrfToken']) {
$password = $Security->Salt($Security->secParam($_POST['password']));
$password = $DB->quoteStr($password);
$email = $DB->quoteStr($_POST['email']);
$DB->Query("SELECT * FROM `table` WHERE `email` = $email AND `password` = $password");
return $DB->GetRow();
}
public function GetRow() {
return mysql_fetch_array($this->last_query);
}
public function quoteStr($str) {
return "'".mysql_real_escape_string($str)."'";
}
Marin Sagovac question is the answer.
To break it down a little more, your var_dump output shows that $results is a nested array. The first part of the output:
array(1) {
[0]=>
shows that $results consists of an array containing 1 element, at index 0, since that's where PHP starts indexing. This is the $results[0] part of Marin's response.
The element 0 of the $results array consists of an array with 8 elements.
[0]=>array(8) {
[0]=> string(1) "1" ["id"]=> string(1) "1"
[1]=> string(35) "email#email.com" ["email"]=> string(35) "email#email.com"
Even though there are only 4 actual results, index 1-4, each one exists twice so that they can either be accessed by index or by its key. Arrays that can be accessed by a unique key, as opposed to an index, are known as associative arrays.
So, in this case, either will return the same value:
echo $results[0]["email"];
echo $results[0][1];
The print_r function would also work, instead of var_dump.