mysql_fetch_array Returning Two Of Everything - php

I'm not exactly new to PHP but I haven't used MySQL that much, so I'll ask you guys about this one.
I have a database with one row of data, which consists of a date and two integers. However, when I query the database with this:
$query = "SELECT * FROM history";
$theQuery = mysql_query($query, $connect);
$array = mysql_fetch_array($theQuery);
... and I do a print_r, I get the following:
Array
(
[0] => 2010-08-17
[date] => 2010-08-17
[1] => 17454
[posts] => 17454
[2] => 1058
[members] => 1058
)
Am I doing something wrong? I plan on having many rows with a ton of data and printing it to a table, THEN how would I go about sorting through it?

First : You did everything right
You can use mysql_fetch_assoc or mysql_fetch_array(resource $result, MYSQL_ASSOC).
The default is to return MYSQL_BOTH (associative array + numeric array).
For more information, see mysql_fetch_array.

The second argument to mysql_fetch_array is optional but default is MYSQL_BOTH and will give you values both for indices and keys. You can use MYSQL_ASSOC instead.
The PHP manual on mysql_fetch_array:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

With mysql_fetch_array, you can run it in a loop ,
ex:
while($array = mysql_fetch_array($theQuery))
{
echo $array["date"];
echo $array["posts"];
echo $array["members"];
}

Related

Array as variable for in_array

I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:
$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
'MailTo1' => 6143,
'MailTo2' => 6137,
'MailTo3' => 6137,
);
echo $mailTo['MailTo1']; //6143
$result1['needle'] = 'MailTo1'; //needle from second query to seek
if(in_array($result1['needle'], $mailTo)){
$id['mailTo'] = $mailTo[$result1['needle']]; //null
}
using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:
if(in_array('MailTo1', $mailTo)){
$id['mailTo'] = $mailTo[$result['needle']]; //6143
}
Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.
$result = 'MailTo1';
if(in_array($result1, $mailTo)){
$id['mailTo'] = $mailTo[$result1]; //null
}
I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...
In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.
array_key_exists("MailTo1",$mailTo)
Another approach would be to get all keys in one array and then you can use in_array()
$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
DOH!!! Wrong approach.. array_key_exists is what I should have been using!!

How to solve array push problem in laravel

i have a Two fields 1. allowances which is contain this data
{"medical":"600","transport":"350","food":"900"}
and another one 2. house rent which is contain this data
2550.00
now i want to get a result in third column like this
{"medical":"600","transport":"350","food":"900","house_rent":"2550.00"}
so far i tried this
$allowances=json_decode($salary->allowances);
$house_rent = array('House Rent' => $salary->house_rent);
$allowances_logs=array_push($allowances,$house_rent);
$salary->allowances_logs = $allowances_logs;
but it gives me following error"array_push() expects parameter 1 to be array, object given". Help me achieve this result. Any help will be appreciated
First, add true as second argument to json_decode(), and you will retrieve the results as an array instead of an object.
Second, with the two arrays, do:
$merged = array_merge($arr1, $arr2);
true Add second argument in json_decode(), so you can see below example
$mainArr = json_decode('{"medical":"600","transport":"350","food":"900"}',true);
$house_rent = array('House Rent' => 2550.00);
$printArr = array_merge($mainArr, $house_rent);
print_r(json_encode($printArr));
Output
{"medical":"600","transport":"350","food":"900","House Rent":2550}
First convert your json to array.
You can do this with json_decode php function.
json_decode function convert your json to object or associative array.
First argument on this function is the json string being decoded.
When is second argument are TRUE, returned objects will be converted into associative arrays.
$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);
Output - Array ( [medical] => 600 [transport] => 350 [food] => 900 )
Now you can add new item to your array.
$testArr['house_rent'] = '2550.00';
Your array now look like this.
Array ([medical] => 600 [transport] => 350 [food] => 900 [house_rent] => 2500.00)
At the end you convert your array to json. For this you can use php json_encode function.
$testJson = json_encode($testArr);
Full Example
$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);
$testArr['house_rent'] = '2500.00';
$testJson = json_encode($testArr);
echo $testJson;

Fetch Casted Value from a select query into an array

I used cast in order to convert a datatype of one of the columns in my select query.
SELECT cast(user_id as varchar(255)) from cabinet
I need to fetch the result of this value into an array but it returns null value
$listData[] = array(
"member_id" => $row['cast(user_id]
);
How can I display it on array?
SQL:
SELECT cast(user_id AS varchar(255)) AS member_id FROM cabinet
PHP:
$listData = array("member_id" => $row['member_id']);
Basically, you forgot to name the cast function's return in your SQL and used some extremely weird syntax in your PHP. $Array[] = $x; adds element $x as an array item to $Array in PHP. To create a new array, you should run $Array = array();. Some programming languages do indeed force you to put square brackets after a variable's name on value assignation to specify it as an Array/String type, but PHP is not one of them.
To reference an item by key, you have to use the array's name and the key's value in square brackets ($Array[$n], where $n is an integer for arrays with integer indexes, and Array['key'] for arrays with String indexes). 'cast(user_id AS varchar(255))' is not a valid array key, you have to give the SQL function return value a name to be able to reference it as an array item.
Please let me know if this makes sense.
My answer assumes that you are familiar with mySQLi and know how to get $row['member_id'] from the query.

mysql_fetch_array returns an array and the number "1"

I have a problem with mysql_fetch_array. I'm trying to do this:
if(count(mysql_fetch_array(mysql_query($peticion)))) {
array_push($errores, $texto['conta_existe']);
}
The previous code should detect if mysql_fetch_array found a row in my database and, if it found at least one, an array should be pushed. Problem is that if I haven't got anything in my db, fetch_array returns the number "1".
I tried to find what's happening with this peace of code:
$arrayc = mysql_fetch_array(mysql_query($peticion), MYSQL_NUM);
echo 'PRINT_R: ';
echo print_r($arrayc);
echo '<br>COUNT: ';
echo count($arrayc);
And returns this:
PRINT_R: Array ( [0] => FLEREX [conta] => FLEREX ) 1
COUNT: 2
I don't understand why there's that number one there, after the array. The previous quote was returned with only one row, to show you the array; but if there's not any row in the db, this is what I get:
PRINT_R: 1
COUNT: 1
I don't know where comes from that one, but is always there.
Thanks for reading and sorry for my bad english.
Try mysql_num_rows instead of count and delete the mysql_fetch_array
mysql_fetch_array doesn't return an array of all the results, it just returns the next row of results, or false if there are no more results. So count() returns the number of columns multiplied by 2 (because the array contains both numeric and associative entries).
Use mysql_num_rows to get the number of rows in the results.
if (mysql_num_rows(mysql_query($peticion))) {

PHP SQLite JSON Data Duplication

I have the following PHP code:
$testMessage = "TESTMESSAGE";
$db = new SQLite3('messages.sq3');
$db->exec('CREATE TABLE messages(id INTEGER PRIMARY KEY, message CHAR(255));');
$db->exec("INSERT INTO messages (message) VALUES ('$testMessage');");
$results = $db->query('SELECT * FROM messages ORDER BY id DESC LIMIT 5');
while ($row = $results->fetchArray()) {
print_r($row);
}
The resulting print_r:
Array ( [0] => 1 [id] => 1 [1] => TESTMESSAGE [message] => TESTMESSAGE )
Why is this data duplicated? Is this just the way the array is presented or are there really two copies of TESTMESSAGE string? Inspecting the sqlite file, I only see one actually stored there. I am trying to serialize the output via JSON and this duplication is carrying through to the serialization.
The default is to have the data with both numeric and string keys, merged in the same array.
You need to use $results->fetchArray(SQLITE3_NUM) or $results->fetchArray(SQLITE3_ASSOC) to get numeric and string keys respectively. The default is SQLITE3_BOTH, which I've always hated.
Both $row[1] and $row['message'] will give you the same data. This is because on technique uses the numerical index of the column and the other uses the name. They are both included in the column so that you can use either way to access them. It does not indicate any sort of duplication in the database itself.
Here you can see the documentation and how to tell PHP which version you want. By default it gives you both: http://php.net/manual/en/sqlite3result.fetcharray.php

Categories