Return a value from a recursive function - php

I have a function that I can get all the correct values for with an echo, but when I cannot figure out how to get the whole array returned. Could someone help me figure out to get the all of the child users?
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
function getchildren($array, $totalarray)
{
foreach($array as $arr)
{
$db_name = "dbname";
$connection = #mysql_connect("localhost", "username", "password") or die(mysql_error());
$db = #mysql_select_db($db_name, $connection) or die(mysql_error());
$sql = "
select *
from users
where creator = '$arr'
";
$result = #mysql_query($sql, $connection) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$newchildren[] = $row['id'];
$totalarray[] = $row['id'];
//echo $row['id'] . ' ';
}
mysql_close();
getchildren($newchildren, $totalarray);
}
}

You need to pass by referenceĀ­Docs:
function getchildren($array, &$totalarray)
^
Usage:
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
var_dump($useridarray); # your result

You need add return before
mysql_close();
return getchildren($newchildren, $totalarray);

I am not familiar with PHP syntax but you likely want to implement a "Stopping Criteria" to return you results. So in your instance it would seem like you would want something where getChildren returns the localResults + recursive getChildren results that are totaled incrementally as you go through your foreach loop.

Related

When row is empty in PHP it should not display anything. When there is something in it, it should display input

function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
if($row["red"] == ""){
echo "";
}else{
while($row = mysqli_fetch_assoc($result)){
echo "<input type='image' src=" . $row["red"]. ">";
}
mysqli_close($con);}}
In PHP I have row "red" filled with link to MShirt/redshirt.png. This code should create an input with this image but if is empty shouldn't create input. Now, this doesn't work even with a filled row.
You have a number of problems with your code, but the main one is that mysqli_num_rows() does not return data. It tells you how many records were fetched from the database into PHP.
You don't need mysqli_num_rows() in your code.
You don't need mysqli_close($con);, especially not inside of the loop.
You don't need the while loop. This is an old way of iterating. Use foreach instead.
You don't need if/else and echo "". You only need the positive condition.
Here is your code fixed:
function getConnection() {
// enabler error reporting, create an instance and set the correct charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('localhost', 'root', '', 'shop');
$con->set_charset('utf8mb4');
return $con;
}
function getRed() {
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = $con->query($sql);
foreach ($result as $row) {
if ($row["red"] != "") {
echo "<input type='image' src=" . $row["red"] . ">";
}
}
}
The function mysqli_num_rows() returns only the count of results returned by your query, the mysqli_fetch_assoc() is the one going through the results. I would suggest taking the mysqli_close($con); outside the if statement as shown.
<?php
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0) {
while($row = mysqli_fetch_assoc($result)){
if(isset($row["red"]) && $row["red"] != "") {
echo "<input type='image' src=" . $row["red"]. ">";
}
}
}
mysqli_close($con);
}
I don't know what this input should work for, but I assume you want to simply embed an image. Use it like this:
$result = mysqli_query($con, $sql);
while ($row= mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
mysqli_num_rows is used to count how many rows are in the result, it returns the number of rows which you can not read like an array...
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
echo $row_count.' rows in result.';
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
Please make sure to understand basic HTML before getting into PHP and MySQL, also do not do database queries without getting to know proper security standards.

while ($data = mysql_fetch_array() ) doesnot working

I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>

PHP returns only the first row from table

<?php
$connection = mysqli_connect("localhost","user","password");
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "database");
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$numeUser = mysqli_query($connection, "select * from table order by column_name");
$utilizator = mysqli_fetch_array($numeUser);
$numeUtilizator = $column_name[1];
$nume = $column_name[2];
$rol = $column_name[5];
$actiune = $column_name[8];
$firstNames = $numeUtilizator;
$lastNames = $nume;
$productNames = $rol;
$actions = $actiune;
$data = array();
$i=0;
while($i < count($firstNames))
{
$row["firstname"] = $firstNames;
$row["lastname"] = $lastNames;
$row["productname"] = $productNames;
$row["quantity"] = $actions;
$data[$i] = $row;
$i++;
}
header("Content-type: application/json");
echo "{\"data\":" .json_encode($data). "}";
?>
I have the code above and I can`t figure why it returns me only the first row from database. It does not show them all. Does anyone please what am I missing?
Thank you very much. Cheers!
A part from the fact that there is no javascript but php.
The mysql_fetch_array (deprecated, no longer exist in php 7) needs to be called in a while loop, look at the documentation, there is your problem, you're only fetching the 1st row.
Another thing, that code is messy, search google for model view controller or model view presenter.
You should never use SELECT * when querying, only select the columns you are going to use.

PHP infinite loop issue

I can get the correct code to work, but i want to be able to use objects and methods, which doesn't work. The same entry in the database is repeated until the query crashes. I saw other people that had queries inside of the while statement, but i thought that the method i am using should only query the statement once, but im likely wrong. Thanks.
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
Seperate class
public function __construct(){
$this->con = mysqli_connect("localhost","root","pass","Minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getUUID($username) {
$result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
return mysqli_fetch_array($result)[0];
}
public function getReports($username) {
$result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
return $result;
}
Each time you call while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) you are making a new query, so it's fetching the samething over and over again.
a solution could be:
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

PHP code works when not put in a function

I am trying to fetch data and encode it to JSON. I have this very confusing trouble. The code I have put in getAnnotions() function, when I do not put it in function, the while loop (commented as //This loop) is reached. Whereas when I encapsulate the same code in getAnnotions() function, that while loop is not reached. What might be the problem?
Here is the code:
<?php
$city=$_GET["city"];
//$limit="1";
//$place=$_GET["place"];
getAnnotions("1");
function getAnnotions($limit)
{
$con = mysql_connect("localhost","hidden","*******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("merrycod_tummy", $con);
$result = mysql_query("SELECT * FROM deal where city_names LIKE '%".$city."%'");
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
$result2 = mysql_query("SELECT locationLat,locationLong FROM place where city ='".$city."' AND name='".$row['place_name']."' LIMIT ".$limit);
while($row2 = mysql_fetch_array($result2))
{
$rows[] = $row2;
//This loop
}
}
echo json_encode($rows);
mysql_close($con);
}
?>
Because $city is defined in the global scope, and in PHP functions variables of another scope cannot be used directly. You can either pass it as a parameter (suggested), or use the global $city at the beginning of your function.
I suggest you to echo the sql in $result first,and then run the code you echo in phpmyadmin to look whether your sql is correct

Categories