select query through function.. to fetch data from db - php

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}

If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}

Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;

Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);

This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}

It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Related

multiple data queries php ajax mysql not working

<?php
$link = mysql_connect("localhost:8889", "root", "root", "Testdata");
if(!link) {echo "Database connexion not possible"; exit;}
$id = $_GET('testeId');
$jsonData = [];
The first query is working:
$jsonData['table1'] = [];
$sql = "SELECT * FROM registerData WHERE testeId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table1'][] = $row;
}
}
else {
$jsonData['table1'][] = "Error 1";
}
This second query is not working:
$jsonData['table2'] = [];
$sql = "SELECT * FROM factsData WHERE factsId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table2'][] = $row;
}
}
else {
$jsonData['table2'][] = "Error 2";
}
mysqli_free_result($result);
echo json_encode($jsonData);
The jsonData string only includes the 1st query:
mysqli_close($link);
The responseText of the ajax request only has data from "table1" array

Query does not output time

I cannot get the
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskDateCreated[] = $row;
}
to output the time once the user has submitted the form. I'm not sure whereabouts exactly the problems lies as the other two $result work as they return the text entered into the field.
How can I get the $result to return the value of the datetime?
<?php
class ProjectBody {
public $mTasks = array();
public $mTaskName = array();
public $mTaskDateCreated = array();
public function __construct() {
if(isset($_POST['task_name']) && isset($_POST['task'])) {
$task_name = DatabaseHandler::escape($_POST['task_name']);
$task = DatabaseHandler::escape($_POST['task']);
$query = "INSERT INTO `project` (name, task, date_created) VALUES ('$task_name', '$task', NOW())";
$result = DatabaseHandler::query($query);
}
$query = "SELECT * FROM `project` ORDER BY `id` DESC";
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskName[] = $row;
}
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()){
$this->mTasks[] = $row;
}
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskDateCreated[] = $row;
}
}
}
?>
Thanks.

Returning mysqli results outside of function

Given the following code:
function fetchData($mysqli){
$sql = "select * from `test`";
$result = mysqli_query($mysqli,$sql);
return $result;
}
$result = fetchData($mysqli);
while($row = mysqli_fetch_array($result)){
echo $row['id'];
}
My code is obviously more complicated than this. It loops itself until it yields some results changing some variables at each iteration.
$result is empty. What am I doing wrong? Thank you!
FULL CODE:
function fetchItem($itemID, $period, $mysqli){
$periodArray = array('7', '30', '60', '90', '180');
while (current($periodArray) !== $period) next($periodArray);
$currentPeriod = current($periodArray);
$sql = "SELECT * from `test` where `period` = '$period'";
$result = mysqli_query($mysqli,$sql);
$row_count = $result->num_rows;
if($row_count < 5){
$currentPeriod = next($periodArray);
fetchItem($itemID, $currentPeriod, $mysqli);
} else if($row_count >= 5){
$currentPeriod = current($periodArray);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// var_dump($rows); <-- returns all results
return $rows;
}
}
$output = fetchItem($itemID, $period, $mysqli);
echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';
As you can see if I don't get results for a given period it moves onto the next one.
Your code should be:
function fetchData($mysqli){
$sql = "select * from `test`";
$init = mysqli_query($mysqli, $sql);
$result = $init->fetch_array(MYSQLI_ASSOC);
return $result;
}
$result = fetchData($mysqli);
foreach($result as $row){
echo $row['id'];
}

How to return a multidimensional array keys as a tree?

I am working on an MLM application in which i need to show all users as a tree. For this is implemented parent child relationship among the users. my table structure is here :-
I had retrieve the id's of users in a multidimensional array as per the relation. Here is array:-
For this i used this code :-
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 )
{
$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id']);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
Now, i need to show the data in a tree structure like :-
Any hint will be helpful. I am very near to complete this...
Yes, you are so near..!!
Try below it will be work for you..
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 ,$result_array = array())
{
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'],$result_array);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
?>
If this will not work for you than let me know..!!
Thanks..
try that, it should give you the structure;
function create_tree( $parent_id = 0 , $result_array = array() )
{
//$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'], $result_array[$row['user_id']]);
}
}
}
return $result_array;
}
edit; forgot the remove result_array in function

check table from my sql query

Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?
To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}

Categories