i have this table produced from the query SELECT * FROM myTable
+--------------------------+---------+--------+
| Name | Version | Detail |
+--------------------------+---------+--------+
| name0 | 10 | xxx |
| name1 | 30 | yyy |
| name2 | 30 | zzz |
| name3 | 30 | kkk |
+--------------------------+---------+--------+
so, i need to have this table in a php array using mysqli function.
//$this->internalDB have the db connection
$result = $this->internalDB->query($query)->fetch_array(MYSQLI_NUM);
print_r($result);
produced
Array ( [Name] => name0 [Version] => 10 [Detail] => xxx )
cycles with the speech does not change ...
how i can do that?
This will query a database and return your values as an associative array in the $arrReturn variable.
$mysqli = new mysqli("host", "user", "password", "database");
$query = "SELECT * FROM myTable";
$sqlRes = $mysqli->query($query);
if (is_object($sqlRes)) {
$arrReturn = array();
while ($row = $sqlRes->fetch_assoc()) {
$arrRow = array();
foreach($row as $field => $value) {
$arrRow[$field] = $value;
}
$arrReturn[] = $arrRow;
}
echo $arrReturn[0]['Name']; // prints 'name0'
}
It might be helpful to read through the mysqli quickstart guide
Related
I have a MySQL table:
-------------------
|type_id|type_name|
-------------------
| 22 | Toyota |
| 22 | Mazda |
| 23 | Volvo |
| 23 | Man |
| 25 | Scania |
| 25 | Iveco |
| 25 | Fiat |
-------------------
which is created dynamically from user input. I want to create an array from the table using PHP like this:
array(
'22' => array('Toyota', 'Mazda'),
'23' => array('Volvo', 'Man'),
'25' => array('Scania', 'Iveco','Fiat'),
);
where array id will be type_id and elements will be type_name's of the type_id.I tried this:
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$results[] = $line;
}
print_r($results);
But I am getting:
Array (
[0] => Array (
[type_id] => 22
[type_name] => Toyota
)
[1] => Array (
[type_name] => 22
[type_name] => Mazda
)
...so on
Please help!
You need to change your code a bit and it will work fine:-
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$results[$line['type_id']][] = $line['Type_name']; //check change here
}
print_r($results);
Note:- check your column-names and correct them if any mistake is there.
Please replace your db name and table name in the code-
$conn = mysqli_connect("localhost","root","","dbname");
$query ="select * from table";
$exe = mysqli_query($conn,$query);
$input = array();
$type = array();
while ($result = mysqli_fetch_array($exe))
{
if(array_key_exists($result['type_id'], $input))
{
$type[] = $result['type_name'];
}
else
{
$type = array($result['type_name']);
}
$input[$result['type_id']] = $type;
}
echo "<pre>";
print_r($input);
select type_id and Type_name columns from table and in foreach loop do this:
$output = array();
foreach ($result as $item){
$output[$item['type_id']][] = $item['Type_name'];
}
How would I make an infinite recursion loop using php and mysql to build a specific array layout? I have writting out my tables, array layout and my attempt at getting this work. I have spent the last few hours working on this but am having no luck.
I am trying to build a php array based on my database that builds a specific layout when using json_encode
My Database tables look like the following
TABLE `info` | TABLE `relations`
+--------+-----------+ +--------+-----------+
| id | name + | id | parent_id |
+--------+-----------+ +--------+-----------+
| 2p03Me | sue | | b5ET7N | 2p03Me |
| b5ET7N | john | | h7S4bk | b5ET7N |
| h7S4bk | bob | | iMz4d7 | 2p03Me |
| iMz4d7 | sam | | ixRpaH | iMz4d7 |
| ixRpaH | teddy | | k41BhX | ixRpaH |
| k41BhX | dan | +--------+-----------+
+--------+-----------+
The generated array should look something like the following:
Array
(
[0] => stdClass Object
(
[text] => sue
[nodes] => Array
(
[0] => stdClass Object
(
[text] => john
[nodes] => Array
(
[0] => stdClass Object
(
[text] => bob
)
)
)
[1] => stdClass Object
(
[text] => teddy
[nodes] => Array
(
[0] => stdClass Object
(
[text] => dan
)
)
)
)
)
)
I have tried this a few times but I can't seem to get this to work. My latest and last attempt was
$tree = category_tree($mysqli, $origSnippet);
function category_tree($mysqli, $catid, $tree = array()) {
?><pre><?php print_r($tree); ?></pre><?php
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_snippet_id`='$catid'";
$children = $mysqli->query($sql);
while($child = $children->fetch_assoc()) {
$tree[] = array('text' => "$child[name]/$child[id]");
echo "$child[name]/$child[snippet_id]<br/>";
category_tree($mysqli, $child['id'], $tree);
}
return $tree;
}
Any help you may be able to provide would be very appricated.
## My Question ##
How would I make an infinite recursion loop using php and mysql to build a specific array layout? I have writting out my tables, array layout and my attempt at getting this work. I have spent the last few hours working on this but am having no luck.
I was able to resolve this problem by doing the following:
$tree = array();
$node_id = 0;
$origSnippet = "2p03Me"; //THIS IS GOTTEN FROM A SEPERATE FUNCTION BUT WILL BE THE STARTING POINT OF THE LOOP
function hasChildNodes($mysqli, $snippetID) {
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_id`='$snippetID'";
return $mysqli->query($sql)->num_rows;
}
function buildTree($mysqli, $snippetID, $node_id, &$tree) {
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_id`='$snippetID'";
$snippets = $mysqli->query($sql);
while($snippet = $snippets->fetch_assoc()) {
$tree[$node_id] = Array("text" => $snippet['name']);
if (hasChildNodes($mysqli, $snippet['id']) >= 1) {
buildTree($mysqli, $snippet['id'], 0, $tree[$node_id]['nodes']);
}
$node_id++;
}
}
$sql = "SELECT * FROM `info` WHERE `id`='$origSnippet' LIMIT 1";
$origSnippet = $mysqli->query($sql)->fetch_assoc();
$tree[$node_id] = Array("text" => $origSnippet['name']);
if (hasChildNodes($mysqli, $childSnippet) >= 1) {
buildTree($mysqli, $childSnippet, $node_id, $tree[$node_id]['nodes']);
}
I wanna count idf, the formula is IDF=log(D/df) that D is total data and df is many data that contain the searched words.
from the tables :
1. tb_stemming
===========================================================================
|stem_id | stem_before | stem_after | stem_freq | sentence_id |document_id|
===========================================================================
| 1 | Data | Data | 1 | 0 | 1 |
| 2 | Discuss | Discuss | 1 | 1 | 1 |
| 3 | Mining | Min | 1 | 0 | 2 |
===========================================================================
here's the code :
countIDF($total_sentence,$doc_id);
that $total_sentence is
Array ( [0] => 644 [1] => 79 [2] => 264 [3] => 441 [4] => 502 [5] => 18 [6] => 352 [7] => 219 [8] => 219 )
function countIDF($total_sentence, $doc_id) {
foreach ($total_sentence as $doc_id => $total_sentences){
$idf = 0;
$query1 = mysql_query("SELECT document_id, DISTINCT(stem_after) AS unique_token FROM tb_stemming group by stem_after where document_id='$doc_id' ' ");
while ($row = mysql_fetch_array($query)) {
$token = $row['unique_token'];
$doc_id = $row['document_id'];
$ndw = countNDW($token);
$idf = log($total_sentences / $ndw)+1;
$q = mysql_query("INSERT INTO tb_idf VALUES ('','$doc_id','$token','$ndw','$idf') ");
}
}
}
and the function of countNDW is :
function countNDW ($word) {
$query = mysql_query("SELECT stem_after, COUNT( DISTINCT sentence_id ) AS ndw FROM `tb_stemming` WHERE stem_after = '$word' GROUP BY stem_after");
while ($row = mysql_fetch_array($query)) {
$ndw = $row['ndw'];
}
return $ndw;
}
It can't worked well, especially in call from database. All I need is to count in every document_id. How to define it in my code ? please, help me.. thank you so much :)
I have sentence table :
======================================================================
| id_row | id_document | id_sentence | sentence |
======================================================================
| 1 | 1 | 0 | Example sentences A |
| 2 | 1 | 1 | Example sentences B |
| 3 | 2 | 0 | Example sentences C |
| 4 | 2 | 1 | Example sentences D |
======================================================================
I wanna merge sentence that have same id_document into array like => Array( [1] => Array ( [0] => Example sentences A [1] => Example sentences B ) [2] => Array ( [0] => Example sentences C [1] => Example sentences D ))
Here's the code :
<?php
require_once 'conf.php';
$sql = mysql_query('SELECT sentence FROM sentence group by id_document') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
$sentence[] = $row['sentence'];
}
print_r($sentence);
?>
but, I just get one sentence in every different id_document. Help me. Thank you :)
Index the array on id_document, and add new entries to the array like this:
while ($row = mysql_fetch_array($sql)) {
$sentence[ $row['id_document'] ][] = $row['sentence'];
}
You can write:
while ($row = mysql_fetch_array($sql))
{
$sentence[$row['id_document']][] = $row['sentence'];
}
while ($row = mysql_fetch_array($sql))
$sentence[$row['id_document']][] = $row['sentence'];
Here's my final code :
<?php
require_once 'conf.php';
$sql = mysql_query('SELECT sentence, id_document FROM sentence ') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
$sentence[$row['id_document']][] = $row['sentence'];
}
print_r($sentence);
?>
Please help me to create an array from a field of my DB. That field has records separated by comma. Below is the illustration:
ID | article_title_fld | article_tags_fld |
----------------------------------------------------------------------
1 | Learn PHP | PHP, coding, scripting |
3 | Javascript Tutorial | Javascript, scripting, tutorial |
4 | Styling with CSS | CSS, tutorial, web design |
I want to collect all records in the article_tags_fld then put it into 1 array. Perhaps I named it $array1, and the print out as below:
Array
(
[0] => PHP
[1] => coding
[2] => scripting
[3] => Javascript
[4] => scripting
[5] => tutorial
[6] => CSS
[7] => tutorial
[8] => web design
)
$array1 = array();
$result = mysql_query("SELECT article_tags_fld FROM MY_TABLE");
while ($row = mysql_fetch_assoc($result)) {
$array1 = array_merge($array1, array_map('trim', explode(",", $row['article_tags_fld'])));
}
explode will split a string by a delimiter.
array_merge will combine two arrays.
array_map will apply trim to all elements.
trim will remove any white space on either side of your tags.
Actually, I would normalize the table into multiple tables first.
articles
article_ID | article_title_fld |
----------------------------------------
1 | Learn PHP |
3 | Javascript Tutorial |
4 | Styling with CSS |
tags
tag_ID | tag_title_fld |
------------------------
1 | PHP |
2 | coding |
3 | scripting |
4 | Javascript |
5 | tutorial |
6 | CSS |
7 | web design |
article_tags
article_ID | tag_ID |
---------------------
1 | 1 |
1 | 2 |
1 | 3 |
3 | 4 |
3 | 3 |
3 | 5 |
4 | 6 |
4 | 5 |
4 | 7 |
and then in the PHP
$array1 = array();
$result = mysql_query("
SELECT tag_title_fld
FROM tags
JOIN articles_tags USING(tag_ID)
ORDER BY article.article_ID
");
foreach($result as $row) {
$array1[] = $row['tag_title_fld'];
// With count. See below for the query it goes with
// $array2 = array();
// $array2['tag'] = $row['tag_title_fld'];
// $array2['count'] = $row['tag_count'];
// $array1[] = $array2;
}
Of course, if you just wanted a list of the tags without duplicates, you'd use this query instead.
SELECT tag_title_fld
FROM tags
and if you wanted them with a count of how often they're used:
SELECT tag_title_fld, COUNT(*) AS tag_count
FROM tags
JOIN articles_tags USING(tag_ID)
GROUP BY tag_title_fld
UPDATED
you can do also this way by using mysql_fetch_Array
$array1 = array();
$result = mysql_query("SELECT ID , article_tags_fld FROM my_table");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$array1[] = $row['article_tags_fld'];
// OR
// $array1[] = $row[1];
}
ADDED:
in one line:
// use this version to behave as in your example..
$array1 = array_map('trim',explode(',',implode(',',$array1)));
// use this version with array_unique for a non duplicate way...
$array1 = array_unique(array_map('trim',explode(',',implode(',',$array1))));
DISPLAY:
print_r( $array1 );
Array
(
[0] => PHP
[1] => coding
[2] => scripting
[3] => Javascript
[4] => scripting
[5] => tutorial
[6] => CSS
[7] => tutorial
[8] => web design
)
This should output everything.
$pdo = new PDO( /* CONNECTION */ );
$stmt = $pdo->query( 'SELECT article_tags_fld FROM TABLENAME' );
function mapFunc( $row ){ return explode( ',', $row[ 0 ] ) }
$all = array();
foreach( array_map( 'mapFunc', $stmt->fetchAll() ) as $row )
{
$all = array_merge( $all, $row );
}
// $all now holds all of the values.
You should normalize your database table so that you don't have comma-separated values in your rows.
mysql_ functions should no longer be used, so I'll demonstrate mysqli's object-oriented syntax.
If your database values are consistently comma-space separated, then explode() is fine. If you might have leading or trailing spaces in your article_tags_fld values, then you can TRIM() that in your SQL. If you might not have spaces after each comma, then you can explode the strings with preg_split() using a pattern like /, */.
The result set object from a mysqli query is iterable by foreach(), so you can safely avoid making iterated fetch() calls to access the column of data.
By pushing the exploded values with the spread operator (...), the result array will be flat.
If you want to remove duplicate values from the result, you can call array_unique() on the result array after the loop is finished.
Modernized Code: (Full MYSQL + PHP Demo)
$result = [];
foreach ($mysqli->query("SELECT article_tags_fld FROM MY_TABLE") as $row) {
array_push($result, ...explode(', ', $row['article_tags_fld']));
}
var_export(array_unique($result));