PHP code works when not put in a function - php

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

Related

Getting Database in array and using it outside with foreach statement like and Opencart

I have seen the opencart function which can be used outside with html like
<?php
foreach ($categories as $category){
echo $category['image'];
}
?>
i would like to make a function like that in php which i can grab data from database and use it outside. may be it's an array so foreach statement is working on it.
like i have name and age in my database i would like to use it like this
<?php
foreach($peoples as $people){
echo $people['name'];
echo $people['age'];
}
?>
Thanks in advance
As Aman Chhabra mentioned, you must first fetch the result from database and then you can use foreach loop to iterate over it.
One thing I would like to mention is DON'T use mysql_query() as use of it is discouraged as per the new guidelines of php development (Check: http://ca1.php.net/manual/en/function.mysql-query.php). To have a compatible code with advanced php use mysqli_query() instead.
Following is the code example utilizing mysqli class. This is procedural way but you can use it in OOP style as well.
//Connect to database
$host = "localhost"; //Change according to yours
$username = "root"; //Change according to yours
$password = ""; //Change according to yours
$database = "test"; //Change according to yours
$con = mysqli_connect($host,$username,$password,$database); //Create the connection
if(!$con)
{
echo "Not connected";
}
else
{
echo "Connected<br />";
}
//Prepare the query to fetch the database records
$query = "select * from TableName"; //Replace the table name with yours
$sql = mysqli_query($con,$query); //Execute the query
while($result = mysqli_fetch_assoc($sql)) //Loop through, till there are records corresponding to the query
{
$rows[] = $result; //Store all the records in an array
}
//Now iterate over each property using foreach loop
foreach($rows as $row)
{
echo "Name - ".$row['name']." Age - ".$row['age']."<br />";
}
Opencart modifies it to the array of results and the use it using foreach
You need to do it like this
$result = mysql_query($con,"SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
$data[] = $result;
}
And then later you can use it like this
foreach($data as $row)
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}

Can't get PHP to return a value

I know that this is an insanely basic question, but I'm new to PHP and am trying to write some simple 'getter' functions that are stored in a separate file.
I keep getting this error, and I can't figure out why.
Fatal error: Function name must be a string in
D:\Hosting\xxxxxxx\html\mysite\scripts\convert_ids.php on line 15
Here is the script from the calling function:
include 'scripts/convert_ids.php';
$group = getGroup(2);
echo $group;
And this is the getter function:
convert_ids.php
<?php
include('connection.php');
function getGroup($id) {
$sql = "SELECT group FROM Groups WHERE id=$id";
$result = mysql_query($sql);
if(!$result) {
return -1;
}
$row = $mysql_fetch_array($result); //<--this is line 15
return $row['group'];
}
?>
$row = $mysql_fetch_array($result);
Should be
$row = mysql_fetch_array($result);
You want to use mysql_fetch_assoc for $row['group']
mysql_fetch_array you will need to use $row[0]
Also don't put a $ in front of mysql_fetch_array

PHP: filtering mysql_query result for specific column?

Is there a quick way to filter a mysql_query result to get a list containing only values of a specific column?
$query = mysql_query("SELECT * FROM users");
$list_of_user_names = get_values($query,"names");
What is the name of the function to be used in place of get_values?
Assuming your field name in databse is "names"
$query = mysql_query("SELECT names FROM users");
while($row = mysql_fetch_assoc($query)){
echo $row['names'];
echo "<br>";
}
NOTE : mysql_* functions are deprecated in new version of php, use mysqli_* or PDO
Use below function.
function get_values($q,$c)
{
$arr = array();
while($row = mysql_fetch_array($q))
{
$arr[] = $row[$c];
}
return $arr; // return all names value.
}
Try this:
$query = mysql_query("SELECT names FROM users");
if (!$query) {
echo "Could not successfully run query from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $names
while ($row = mysql_fetch_assoc($query)) {
echo $row["names"];
}

Return a value from a recursive function

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.

Will this PHP + postgreSQL code work? I'm coding blind!

I have a strange question. I need to send some code to a client without having access to the server to test my code. In addition, it's using postgreSQL which I've never used, and I've not done PHP for a while!
In order to save some time, I'd really appreciate if someone could tell me if this code will do what I want?
example feed
<?
$sql = "SELECT * FROM V_SIDE_MENU_E";
include 'db.inc.php';
?>
db.inc.php
$connectString = 'host=localhost dbname=myDatabase user=foo password=bar';
$link = pg_connect($connectString);
if (!$link) {
echo "error";
} else {
$result = pg_query($link, $sql);
$rows = array();
while($r = pg_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
}
I would change
$rows = array();
while($r = pg_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
into
print json_encode(array_values(pg_fetch_all($result)));
But that's just a style thing -- your code should work.
Tested on your mysql ( it looks like it will work ). Your SELECT will work same in PostgreSQL like mySQL

Categories