Store data after mysql query - php

This is my problem. I have a table in my database in which there are two columns, ID and ANSWER. In this database there are more rows with same ID, so I want to save all the results with this id in an array.
the sql code is:
$sql6 = "SELECT * FROM Answer WHERE userId = :userId and qId = 'q6'";
$stmt6 = $conn->prepare($sql6);
$stmt6->execute(array(':userId' => $_SESSION['SESS_MEMBER_ID']));
now to fatch the results I don't know if I have to use
$result6 = $stmt6->fetch(PDO::FETCH_OBJ);
or
$result6 = $stmt6->fetchAll();
EX.
ID ANSWER
q6 abba
q6 bbaa
i would save in an array like this for example:
$array=("abba","bbaa");
then i would pass this array to a script in javascript.

You can either call $stmt->fetch in a loop, pushing each row onto the resulting array, or you can call fetchAll once -- it returns an array of all the rows. So the following are equivalent:
$array = array();
while ($row = $stmt6->fetch(PDO::FETCH_OBJ)) {
$array[] = $row;
}
and:
$array = $stmt6->fetchAll(PDO::FETCH_OBJ);
If you want an array with just the value of a single column, rather than objects representing the whole row, the loop will be easier:
while ($row = $stmt6->fetch(PDO::FETCH_OBJ)) {
$array[] = $row->q6;
}

#Barmar, your solution partially works. i've written this:
$sql6 = "SELECT * FROM Answer WHERE userId = :userId and qId = 'q6'";
$stmt6 = $conn->prepare($sql6);
$stmt6->execute(array(':userId' => $_SESSION['SESS_MEMBER_ID']));
$count6 = $stmt6->rowCount(array(':userId' => $_SESSION['SESS_MEMBER_ID']));
$answer6 = array();
while ($result6 = $stmt6->fetch(PDO::FETCH_OBJ)) {
$answer6[] = $result6->answer;
}
then i want to pass this array to a script, so:
<script>
var num = var ans6 = '<?php echo $count6; ?>';
var ans6 = '<?php echo json_encode($answer6); ?>';
for(var i=0; i<num;i++){
alert(ans6);
}
the result is a popup in which is written "["abba","bbaa"]".
but if i write
for(var i=0; i<num;i++){
alert(ans6[i]);
}
the popup shows first"[" and then " " "

Related

Get column value from a foreign key reference in PHP

My output is only id column, reference to "combustibili" table. How to get value reference from combustibili?
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}
From information provided assume COMBUSTIBILItable structure should be something like
COMBUSTIBILI(id pk and fk_in_tabelint number, name varchar, price float)
TABELINT(id pk number, ID_BENZINA_STANDARD fk->COMBUSTIBILI number ... etc)
so
SELECT * FROM tabelint where id=1 will retun something like
(id #1, ID_BENZINA_STANDARD #2 ... etc)
and just need to query COMBUSTIBILI with fks
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
//assume also record for id=1 exists
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}
//add for each id_s
//BENZINA_STANDARD :: should be 1 row if db is consistent
//not sure how PGData class is defined and how to retrive only id : maybe $pgd->id ...
//$data = $row["ID_BENZINA_STANDARD"] : this is what is needed
$sql = "SELECT * FROM COMBUSTIBILI where id=".$data;
$sqlout = $conectare->query($sql);
//just parse and retrive what ever wanted
while($row = $sqlout->fetch_assoc()) { ... etc ... }
//same with data2_3_4

creating outer array php

UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);

How to combine multiple SQL SELECT results into one array in PHP?

Hello this code works but currently it is very repetitive.
I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.
I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(
I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select data from table from a random row
$grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
$grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
$grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
$grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
$grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
$grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";
$result1 = $mysqli->query($grab1);
$result2 = $mysqli->query($grab2);
$result3 = $mysqli->query($grab3);
$result4 = $mysqli->query($grab4);
$result5 = $mysqli->query($grab5);
$result6 = $mysqli->query($grab6);
// Convert result into an array called items
$item1 = mysqli_fetch_row($result1);
$item2 = mysqli_fetch_row($result2);
$item3 = mysqli_fetch_row($result3);
$item4 = mysqli_fetch_row($result4);
$item5 = mysqli_fetch_row($result5);
$item6 = mysqli_fetch_row($result6);
I managed to solve this with help on this thread..
I replaced all this code with:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value) {
$grab[$key] = "select * from stock_tbl where stock_id='$value'";
$result = $mysqli->query($grab[$key]);
$item[$key] = mysqli_fetch_row($result);
}
Thank you very much :)
First of all, do you really need *?
What's wrong with using a single query with the IN() function? For example:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select(grab) data from table from a random row
$grab = 'SELECT * FROM stock_tbl WHERE stock_id IN ('.implode(',', $ran_num).')';
<?php
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value)
{
$grab[$value] = "select * from stock_tbl where stock_id='$value'";
}
?>
If you don't need to access each statement individually, this is also possible:
<?php
$ran_num = (RandomInRange(1,$total,6));
$grab = '';
foreach ($ran_num as $key => $value)
{
$grab .= "select * from stock_tbl where stock_id='$value';";
}
?>
That's essentially creating one long string that SQL will parse as individual commands using the semi-colon as the delimiter for each one.
You can concatenate strings in PHP with the '.' operator. Also, setting the grab variables as an array will make this easier as well, if that is possible in your implementation. You're probably looking for code such as:
for (int i=0; i < 20; i++)
$grab[i] = "select * from stock_tbl where stock_id='$ran_num[".i."]'";

php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.
I want to get the records based on these two id number. But this below code returns the output repeatedly.
How do I properly put the while loop code inside a foreach?
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',' ',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array.
$res = mysql_query($sql)
should be on it's own line before the while loop, and then
while($r = msql_fetch_array($res))
This will properly increment through the $res list.
Try this and you are done
As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',',',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories