PHP Function producing two iterations of an array, in the same array - php

I've got a function that gets data from a NoSQL database, and if it's not available then it goes to a MySQL database to get the data but the issue is, the function is putting the data into the array twice and I can't figure out why.
Expected result
array(2) {
["id"]=> string(2) "30"
["username"]=> string(8) "Username" }
Actual result
array(4) {
[0]=> string(2) "30"
["id"]=> string(2) "30"
[1]=> string(8) "Username"
["username"]=> string(8) "Username" }
Code
Code that is irrelevant to the problem is removed and replaced by pseudo code comments.
$Connection = $this->Connect("MySQLi");
$Data = MySQLi_Fetch_Array(
MySQLi_Query($Connection["MySQLi"], $Options["Query"])
);
echo "Got array (MySQLi).";
It's worth noting that the string "Got array (MySQLi)." only appears once.

MySQLi_Fetch_Array gets duplicated data in one array - with numerical and associative indexes at the same time
Use mysqli_fetch_assoc instead to have only associative

mysqli_fetch_array() takes a parameter, resulttype, which by default is set to MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
mysqli_fetch_assoc fetches an associative array, while mysqli_fetch_row fetches an array with numeric indexes.
mysqli_fetch_array with the parameter MYSQLI_BOTH will fetch both named (associative) indexes and numeric indexes in the same array.

Related

Issue passing array as argument [to InvokeArg()] in php - var_dump are the same but only one works?

Backstory: Creating function to handle mysqli and binding data. All code is in the scope of a single function. Using ReflectionClass to programmatically invoke mysqli_stmt_bind_param function (as number of arguments vary).
Problem: I am having an issue passing an array I built up programmatically ($refArr). When I compare the var_dump of this array (with a sample array I created directly), the two arrays are identical. The invokeArg() method runs with the sample array ($refArr_sample) but not with $refArr.
Here is the output for the code shown below:
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr_sample
$refArr_sample = array("si", "user1", 0);
// var_dump are equal in type and length
var_dump($refArr);
var_dump($refArr_sample);
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr); // Doesn't Work ?????????
//$method->invokeArgs($res,$refArr_sample); // Works ?????????
$res->execute();
I am unsure how to fix the problem (as I've no clue what the problem is). I don't think this is an issue with references. Once the var_dump is the same I thought it wouldn't have mattered. I also did a === comparison between the two arrays which came back true. At this point I am lost as to why it isn't working.
I can link the complete code (self contained function) if required.
You should note that the values in the passed array must be references (as of PHP 5.3), whereas your $refArr is built dynamically.
...
//assign references
foreach ($refArr as $key => $value) {
$refArr[$key] =& $refArr[$key];
}
$method->invokeArgs($res,$refArr);
...

php unserialize data from table not working

i need to unserialize a string to an array.Here is the stringwhich needs to be unserialized in php to assosiative array.
a:1:{i:0;s:158:"a:6:{s:5:"rowid";s:32:"94ca9ee0c4e3184b50e89e82f80332fb";s:2:"id";
s:2:"68";s:3:"qty";s:1:"1";s:5:"price";
s:2:"20";s:4:"name";
s:5:"Bread";s:8:"subtotal";i:20;}";
}
It looks like this has been doubly serialized. It expands to an array with a single element, and that element is a serialized associative array. So you need to do:
$temp = unserialize($data);
$result = unserialize($temp[0]);
var_dump($result);
Result:
array(6) {
["rowid"]=>
string(32) "94ca9ee0c4e3184b50e89e82f80332fb"
["id"]=>
string(2) "68"
["qty"]=>
string(1) "1"
["price"]=>
string(2) "20"
["name"]=>
string(5) "Bread"
["subtotal"]=>
int(20)
}
If there can be more that one element in the top-level serialized array, use array_map to unserialize all of them:
$result = array_map('unserialize', $temp);
$result will now be a 2-dimensional array.
I'm not sure why you stored your data this way. Why not just serialize the original 2-d array all at once, instead of nesting them?

Only get field names from MySQL

Right now when I run the following query SELECT * FROM table I get the following response
array(1) {
[0]=>
array(36) {
[0]=>
string(5) "31764"
["id"]=>
string(5) "31764"
...
}
...
}
As you can see I am getting 2 of the same data ("0" and "id"). Is there any way I can only get "id" and not "0"?
Check the documentation of mysql_fetch_array(), the second argument allows you to specify what kind of array to return:
The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
Or you could just use mysql_fetch_assoc().
you can write the sql just like :
SELECT 'id' FROM table
it wil just return

Get value from a array

update
how can I retrieve this value? I need to do that if I will write the value to my database.
array(3) {
[1]=> NULL
[2]=> array(2) {
[123]=>
int(123)
[122]=>
int(0)
}
[3]=> NULL
}
There is something missing in your output. I assume it looks something like:
// var_dump($array);
array(1) {
[0]=>
string(2) "39"
}
so you can access the value with $array[0]. Simple array access.
As arrays are the most important data structure in PHP, you should learn how to deal with them.
Read PHP: Arrays.
Update:
Regarding your update, which value do you want? You have a multidimensional array. This is what you will get:
$array[1] // gives null
$array[2] // gives an array
$array[2][123] // gives the integer 123
$array[2][122] // gives the integer 0
$array[3] // gives null
Maybe you also want (have) to loop over the inner array to get all values:
foreach($array[2] as $key => $value) {
// do something with $key and $value
}
As I said, read the documentation, it contains everything you need to know. Accessing arrays in PHP is not much different than in other programming languages.
The PHP manual contains a lot of examples, it is a pretty could documentation. Use it!
If your array is referenced as $myArray, you can get the string 39 via $myArray[0], i.e., this zeroth item.

PHP var_dump array

array(14) {
[0]=>
string(1) "1"
["id"]=>
string(1) "1"
[1]=>
string(7) "myUserName"
["UserID"]=>
string(7) "myUserName"
[2]=>
string(10) "myPassword"
["passwordID"]=>
string(10) "myPassword"
[3]=>
string(24) "myEmail#domain.com"
["emailAddress"]=>
string(24) "myEmail#domain.com"
[4]=>
string(7) "myFirstName"
["firstName"]=>
string(7) "myFirstName"
[5]=>
string(8) "myLastName"
["lastName"]=>
string(8) "myLastName"
[6]=>
string(1) "1"
["active"]=>
string(1) "1"
}
how do i access the contents of this array using PHP?
the above was a var_dump($info)
It depends on which part of the array you are trying to access.
If you are trying to access a specific item, you can access it by its index ; for instance :
echo $info['passwordID'];
Should give you :
myPassword
(edit after the comment)
For the email address, there is this portion in your var_dump's output :
["emailAddress"]=>
string(24) "myEmail#domain.com"
This indicates that the e-mail address is stored in the array as an element that has the key "emailAddress".
Which means you should be able to get that e-mail address like this :
echo $info['emailAddress'];
And as you also have this portion of text in the var_dump's output :
(About that duplication of data, you should read Pekka's answer, who provides an idea of why your data is in your array twice, with both integers and strings as keys)
[3]=>
string(24) "myEmail#domain.com"
You could also use :
echo $info[3];
(of course, in each of those cases, you could also store this to a variable for futures re-use)
Another solution, if you want to access each item, would be to use some foreach loop ; for instance :
foreach ($info as $key => value) {
echo "Value for key $key is $value <br />";
}
You might want to go through the arrays section of the PHP manual, for more informations.
And, also, the section about array functions.
You can use either the numeric or the associative key:
echo $array[0]; // outputs 1
echo $array["id"]; // outputs 1
I'm guessing this is the result of a mysql_fetch_array() operation, isn't it? You may want to specify whether you want a numeric or associative array using the second parameter to that function.
Example:
$record = mysql_fetch_array($query, MYSQL_ASSOC); // for associative keys only
$record = mysql_fetch_array($query, MYSQL_NUM); // for numeric keys only
The array appears to have both string and numeric keys. You can access the fields using the array index operator []. Supply either the numeric key or the column name:
echo $info['UserID']; // output "myUserName"
echo $info['emailAddress']; // output "myEmail#domain.com"
if $info is the array, then you can echo $info[6] for example.
If you want it as a string then $s=print_r($info,true);
It seems you are doing some thing wrong, as there shouldn't be a need to access array like that, and there other ways to access objects as arrays.

Categories