Returning mysqli results outside of function - php

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'];
}

Related

Why is this piece of code giving me duplicate results?

This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>

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.

select query through function.. to fetch data from db

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

function call inside a function in php not working

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!
Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.
You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

Return results from mysql, using user functions

Please tell, why this code is wrong?
function myres () {
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
return $res;
}
while ($row = myres()->fetch_row()) {
echo $row[0];
}
P.S.
this code is working:
$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
while ($row = $res->fetch_row()) {
echo $row[0];
}
Here you call myres() every time, I think:
while ($row = myres()->fetch_row()) {
echo $row[0];
}
So every time $row contain first row of the result, and it will not stop. It will works fine, I think:
$res = myres();
while ($row = $res->fetch_row()) {
echo $row[0];
}

Categories