I tried this:
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
var_dump($values);
echo $values;
?>
But I got this on my webpage:
C:\wamp64\www\site\site.php:18:
array (size=2)
0 => int 1
'' => int 1
Am I missing something?
$values is an array, so you need to access the direct value if you want to echo it. The max ID is 1, as shown by your var_dump() - but you get two results from the array $values, one associative and one numeric indexed. If you alias your data from the query, you can then fetch the associative value by name of that alias.
<?php
$query = "SELECT MAX(ID) as maxID FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values['maxID'];
Or if you want to access it numerically,
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values[0];
Related
I'm trying to create an array from the results of 2 queries, and send it all together to front-end, but I'm stuck to the point where I need to push the results of the second query to the array, I tried to do it using array_push but doesn't work.
Let's say we have this example, and I need to include the results of $query2 to $return_arr
Any ideas?
<?php
header('Access-Control-Allow-Origin: *');
include "config.php";
$return_arr = array();
$query1 = "SELECT * FROM balance WHERE class='income' ORDER BY id DESC";
$query2 = "SELECT * FROM balance WHERE class='expense' ORDER BY id DESC";
$result1 = mysqli_query($conn,$query1);
while($row = mysqli_fetch_array($result1)){
$id = $row['id'];
$description = $row['description'];
$date = $row['date'];
$euro = $row['euro'];
$who = $row['who'];
$class = $row['class'];
$return_arr[] = array("id_income" => $id,
"description_income" => $description,
"date_income" => $date,
"euro_income" => $euro,
"who_income" => $who,
"class_income" => $class
);
}
// Encoding array in JSON format
echo json_encode($return_arr);
Here's a different query:
SELECT *
FROM balance
WHERE class IN('income','expense')
ORDER
BY class
, id DESC
Like JS Bach answer. But maybe you could speed up performance by mention the column's name.
SELECT column1, column2, column3 FROM balance WHERE class IN ('income','expense') ORDER BY class, id DESC;
You can also make use of OR operator
$query = SELECT * FROM balance WHERE class = "income" OR class = "expense" ORDER BY class, id DESC;
$result = mysqli_query($conn,$query);
$array = mysqli_fetch_array($result,MYSQLI_ASSOC);
Your fetched records will already be in an array format in $array
This can be more effective when dealing with tables having records in 1000s of rows
How to make the array of id that we call from a table?
What I want is like this :
$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.
Thank you
Code :
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){
$a = implode(',',(array)$row['id_add_user']);
echo $a;
}
What I get from echo $a is 12345 not 1,2,3,4,5
Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.
$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id_add_user']);
}
echo implode(", ", $result);
Collect necessary values into an array.
$a = [];
while(...){
$a[] = $row['id_add_user'];
}
echo implode(',', $a);
You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL
You can further simplify it to...
$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));
mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.
$array = array(1,2,3,4,5);
Use below SQL query for selecting the array id data
SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;
i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}
I have a query:
$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";
Which result in:
sponsored plan
2 gold
1 silver
1 mitra
This result is shown when I run this query in MySQL.
Now I want this result in PHP in an array data[] where
data[0] contains 2
data[1] contains 1
data[2] contains 1
I have tried this
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
while($data = mysqli_fetch_assoc($res)) {
echo $data['sponsered'];
}
But it results in data['sponsered'] containing 211
It would be better if this can be done without using any loop.
Inside the while loop assign the values to array.
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
$data = array();
while($result = mysqli_fetch_assoc($res)) {
$data[] = $result['sponsered'];
}
print_r($data);
Output:
data[0] contains 2
data[1] contains 1
data[2] contains 1
Your display is correct you just need a separator so the data isn't all clumped. In a browser:
echo $data['sponsered'] . "<br>";
in your loop should do it, or command line,
echo $data['sponsered'] . PHP_EOL;
should do it.
As is it throws 2, then 1, then 1 which views as 211.
Try this:
Please refrain from passing data directly into query in a prepare statement, use ? or : as deemed necessary.
Below is a sample code:
<?php
$table_name = $table; //not recommended to pass table_name as variable, unless necessary.
$parent_id = 2;
$p = $plan;
$string = "SELECT COUNT(id) as sponsered FROM $table_name where parent_id = ? group by ?";
if ($stmt = $db->prepare($string))
{
$stmt->bind_param('is', $parent_id, $p);
$stmt->execute();
$stmt->bind_result($sponsored, $plan);
$stnt->store_result();
$html ='';
while ($stmt->fetch() !== FALSE)
{
// Do what you like with the variables here, i.e. $sponsored, $plan
$html .= "<table>
<th> Sponsored </th>
<th> Plan</th>
<tr>
<td>$sponsored</td>
<td>$plan</td>
</tr>
</table>";
}
else {
die("Query failed");
}
var_dump($html);
}
?>
NOTE: If your result from your question is just an HTML (table/column), you don't need to do bind, you can just output the HTML formatted.
Use mysqli_fetch_array($result, MYSQLI_NUM) to retreive the data as numeric array
i have this table
Column_1 Column_2
1 value1
2 value1
3 value2
My php query is
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
print_r($query);
This returns only the 1st row. I am looking to display row 1 and 2. When I run the SQL in phpmyadmin it returns row 1 and 2. However, the php script only returns row 1... I also did an
echo count($query);
But it returns only 1. What am i doing wrong?
$query = "SELECT * FROM `table` WHERE `Column_2` = 'value1' ";
$res = mysql_query($query);
if(mysql_num_rows($res)!=0) {
while($rowData = mysql_fetch_array($res)) {
var_dump($rowData);
}
}
Use mysql_num_rows to count number of results.
Use mysql_fetch_array or mysql_fetch_assoc to fetch data.
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_assoc())
print_r($row);
You need add fetch in cycle.
Use mysql_fetch_array() function
$query = "SELECT * FROM `table` WHERE `Column_1` = 'value1' ";
$res = mysql_query($query);
while($row = mysql_fetch_array($res))
{
echo $row['Column_1'];
echo $row['value_1'];
}