i want to select a randomly data using php - php

I need help in selecting a random data from the table
Let's suppose There are 10 columns in my table but i want that if I hit the query sometime it will bring all data and sometime it will bring data only from 1 column and some time from the no 1 and no 2 column
How can I achieve this?
Thanks in advance
function selectAllInventoriesINGroup($conn,$groupname,$import_id)
{
$cgstSgst = explode('-', $groupname);
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
$result = $conn->query($sql);
$jsonxx = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $jsonxx ;
}
I have tested this but it fetch the all the data from the database
<?php
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
?>

Related

How can I create an array from the results of 2 queries?

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 sum of MySQL table column in php?

I want to get the sum total of the table columns in my database.
I've tried using the following code but have not been successful.
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM User_Table');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
Thank you very much!!
I hope you try to find total number of record of a table of User_Table
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM User_Table');
//or like the query for return last row that indicate total number of record
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;');
$row = mysqli_fetch_assoc($result);
$sum = $row['id'];
echo $sum;
// or using count
$result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;');
$row = mysqli_fetch_assoc($result);
$sum = $row['total_row '];
echo $sum;
As of my understanding you need count the number of columns your database have. If I am not wrong, you may please use the query below
select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position
Hope this helps. Thanks

get required result in sql

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);
}

Error: Array to string conversion error

Firstly I am randomly selecting the ID from my table. That part works fine but the next part doesn't. The next part is selecting the ID's row, e.g. if the ID is 6, then it should select all the fields related to 6.
my table is like this:
------------------------------
|ID|Name|Email |Password|
------------------------------
|1 |Amy |H#gmail.com|jaaaaaaa|
------------------------------
|2 |Bob |1#gmail.com|haaukanm|
------------------------------
|3 |Bill|aa#mail.com|fsoji443|
------------------------------
This is my code:
<?php
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
?>
The issue is here:
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
here $data2 is not a single value, its an array and you are trying to compare it in WHERE like a string, that's why the error. Instead try $data2['id'] like:
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
or
$c = "SELECT * FROM `tblaccounts` WHERE ID=".$data2['ID']; // Sinlge quote is not required if `ID` is `int`
Because your $data2 is an array, this is should work
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
You are getting this error as you are comparing array in where clasue.
Your $data is an array like below
$data = array(
'ID'=>2
'Name'=>'Bob',
'Email'=>'1#gmail.com',
'Password'=>'haaukanm'
);// say record with id 2 is fecthed
So use $data['ID'] in your where clause

Sum fields from different tables per userID

Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}
You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";
You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial

Categories