Fetch data from mysql using associative array and implode (codeigniter + MySql) - php

I've gathered data from multiple MySql tables and stored them as associative arrays using a foreach loop with the query.
I would like to use those associative arrays and the implode method in the mysql query to gather more data from a separate table.
I know that with the implode method, when dealing with Indexed arrays, you can just insert the array directly in the "implode section". But with associative arrays, I am unsure how to call all the available arrays and insert them in the query.
Please refer to the attached image for a detailed illustration explaining it further.
Below is also a portion of my code
public function user_implode()
{
$s_id = array(
"id" => 383
);
$count = 0;
foreach ($query->result() as $row)
{
$count = $count + 1;
$loop_number[$count] = $row->id;
}
$this->db->from('occupation');
$this->db->where_in('id',implode("','",$loop_number[$count]));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->id;
}
echo 'Total Results: ' . $query->num_rows();
}
THANKS ALOT

The second parameter to where_in() should be an array.
You are generating a string with implode() and only of the last value of the array instead of the whole array.
So all you need is:
$this->db->where_in('id', $loop_number);
And I don't see where $query comes from, it seems to be undefined when you use it in the first loop in your method.
Apart from that you should initialize your variable, $loop_number = []; before the loop.

Related

How to loop mysql result inside an array

I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?
You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO
You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

How to print only index of an array

Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}

Passing each row of a mysql query to a php array

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}

PHP/MySQL: How to get multiple values from a PHP database method

Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>

Categories