Can't echo single value from array with a function in PHP - php

I am having trouble with PHP, where I populate an array with results from a MySQL query.
The problem is when I make a function to echo a certain element of the array, it's not working, where as without a function there are no errors.
Establish connection, perform query, store result in variable:
require_once("db.php");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM arlista";
$query_result = mysqli_query($conn, $query);
mysqli_close($conn);
$result_array = array();
I pass the query results to an array, then I want to query a single value from the array. The problem is if I use a function like this, this does not work. I can't get the element of the array to display in the browser.
function arlista($attr, $rownum){
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row[$attr];
$i++;
}
echo $result_array[$rownum];
}
arlista("ar",1);
However this works if I do not use a function. The browser is displaying the value.
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row["ar"];
$i++;
}
echo $result_array[1];
Could someone explain what is going wrong with the function or how do I fix it to work? Thank you!
The server is running PHP 5.6.19

Check your variable scoping. Your function has no variable $query_result. Turning on error reporting would also give you notices about the problem.
Using a global would work:
function arlista($attr, $rownum){
global $query_result, $result_array;
while($row = mysqli_fetch_array($query_result)){
$result_array[$i] = $row[$attr];
$i++;
}
echo $result_array[$rownum];
}
arlista("ar",1);
Hope that helps!

A function does not bring in the variables that you haven't defined inside the function, or passed in. Since you did not define or pass in $query_result and $result_array, the script would not work. However, without the function, that variable is defined, so the script will work. To make the function work, all you need to do is pass in the variable $query_result, $result_array or define it inside the function.
Edit: As Adam said, you can define in the function to use it as a global variable:
global $query_result, $result_array;

You need to pass $query_result as an argument to the function. You should also initialize the variables that you use within the function. But there's no real need for the $i variable, since you can use [] to push a new element onto an array.
function arlista($attr, $rownum, $query_result){
$result_array = array();
while($row = mysqli_fetch_array($query_result)){
$result_array[] = $row[$attr];
}
echo $result_array[$rownum];
}
arlista("ar", 1, $query_result);
You could also use global $query_result, but explicit arguments are generally better programming style.

You need to either pass $query_result as a function parameter, or define it as a global variable within the function.

Related

How to return empty array or resultset from a query with mysqli_fetch_all()?

My PHP code:
function get_something() {
global $link;
$sql = "SELECT * FROM new";
$result = mysqli_query($link, $sql);
$names = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $names;
}
What is my problem:
When my table new is empty, I get the following error:
mysqli_fetch_all() expects parameter 1 to be mysqli_result`
If it isn't empty everything is working fine.
I need to check if my database is empty and if it's not, I will call mysqli_fetch_all. Otherwise, my function should return an empty array.
How is this possible to do?
Use mysqli_num_rows($result) to check how many rows were returned from the query. But if table new doesn't exist, $result will be false so we have to check that $result is valid as well:
if ($result && mysqli_num_rows($result) > 0)
$names = mysqli_fetch_all($result, MYSQLI_ASSOC);
else
$names = array();
return $names;
mysqli_fetch_all($result, MYSQLI_ASSOC) generates an indexed array of associative arrays. When there are no rows found, it will deliver an empty array (which is what you want). It is absolutely pointless to call mysqli_num_rows(), so don't make your script do any unnecessary work.
Furthermore:
many developers will advise you not to make global declarations to pass variables in your custom function scope. Instead, pass the connection variable into your function as a parameter.
I always try to avoid declaring single use variables. For your case, $sql and $names will only be used/referenced once after being declared, so just don't declare them.
As a matter of personal preference, I recommend using OO syntax with mysqli functions because it is less verbose, but in my following snippet I'll leave it like your original post.
Suggested Code:
function get_something($link) {
if (!$result = mysqli_query($link, "SELECT * FROM new")) {
return []; // check mysqli_error($link) because your query failed
}
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

PHP works outside function but wont work inside function

I'm trying to put the following code into a function as I need to use it quite a few times but with one variable changed ($subject) but it doesn't seem to be working. If I remove it from the function and run it, it works fine but as soon as it goes into the function and gets called it breaks so I'm not sure there is anything wrong with the code itself. I'm new to using PHP functions, but do I need to pass in everything or can it access variables outside of the function such as the $connect and $id variables which are defined above?
function count($subject){
$getCount = $connect->prepare('SELECT count(*) FROM entries WHERE uid = :id AND subject = :subject');
$getCount->execute(array(
':id' => $id,
':subject' => $subject
));
$rowCount = $getCount->fetchColumn();
return $rowCount;
}
echo count("English");
$connect is no longer accessible inside the function. A simple, but bad fix would be this:
function count($subject){
global $connect
A better fix would be for you to send in the $connect variable to the function:
function count($subject, $connect){
And change your function calls to
count("The subject", $connect)

custom function for mysqli queries

I'm trying my hand at custom functions in PHP in order to streamline a lot of stuff I'm otherwise doing manually. I'm damn new to custom functions so I'm not sure the limitations. Right now I'm trying to get data with MySQLi using custom functions Here's the code, and then I'll explain the issue:
function connect_db($db = 'db_username') {
iconv_set_encoding("internal_encoding", "UTF-8");
mb_language('uni');
mb_internal_encoding('UTF-8');
# $mysqli = new mysqli('host',$db,'password',$db);
if(mysqli_connect_errno())
{
die('connection error');
}
}
This one seems to be working fine. It's the next function I'm having more trouble with.
edit: Updated thanks to Jeremy1026's response
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
My host forces database names and usernames as the same, so if the db name is 'bob' the username to access it will be 'bob' as well, so that's why $db shows up twice in the connection.
The problem I'm having is that these two functions are in functions.php and being called from another page. I want to be able to pull the results from the query in that other page based on the column name. But I also need to be able to do this with formatting, so then maybe the while() loop has to happen on that page and not in a function? I want this to be as universal as possible, regardless of the page or the data, so that I can use these two functions for all connections and all queries of the three databases I'm running for the site.
God I hope I'm being clear.
Big thanks in advance for any suggestions. I've googled this a bit but it's tough to find anything that's not using obsolescent mysql_ prefixes or anything that's actually returning the data in a way that I can use.
Update: I'm now getting the following error when accessing the page in question:
Fatal error: Call to a member function query() on a non-object in /functions.php`
with the line in question being $result = $mysqli->query($query);. I assume that's because it thinks $query is undefined, but shouldn't it be getting the definition from being called in the page? This is that page's code:
$query = "SELECT * FROM `table`";
$myArray = do_query($db, $query);
echo $myArray['column_name'];
In your 2nd function you aren't returning any data, so it is getting lost. You need to tell it what to return, see below:
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
Then, when using the function you'll do something like:
$myArray = do_query($db, 'select column from table');
$myArray would then be populated with the results of your query.
This is a half-answer. The following single function works in place of the two.
function query_db($database, $new_query) {
$sqli = new mysqli('host', $database, 'password', $database);
$sqli->set_charset("utf8");
global $result;
if($result = $sqli->query($new_query)){
return $result;
}
}
By adding global $result I was able to access the results from the query, run from another page as
query_db("username","SELECT * FROM `column`");
while($row = $result->fetch_assoc()){
print_r($row);
}
It's more streamlined than I have without functions, but it's still not idea. If I have the connection to the database in another function, it doesn't work. If I try to put the while loop in the combined function, it doesn't work. Better than nothing, I guess.

How to put mysql inside a php function?

I have problem about putting mysql into a function showMsg(). The mysql is working fine if it is not wrapped by function showMsg(), but when I wrap it with function showMsg(), it gives error message "Warning: mysql_query(): supplied argument is not a valid". How to put mysql inside a php function? Below is my codes :
<?php
function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
<div>
<?php showMsg(); ?>
</div>
?>
Never use global.
Pass $connection into your function as an argument.
Logic and representation should be separated.
Read about MVC: here or here.
Global variables are evil, never use it. If someone suggests it - ignore all their answers.
You probably need:
global $connection;
(Inside the function, that is.)
See Variable Scope
As everyone mentioned, the issue has to do with variable scoping. Instead of add global $connection; you could consider a more OOP approach and consider:
A: passing the $connection variable into the function.
B: placing related functions in a class and pass the DB connection into the Class constructor.
for example:
class YourClass {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$this->connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
}
I don't have enough rep to comment. But I also like OZ_'s answer :)
$connection variable has no value assigned. The following code should solve your problem (add it at the beginning of the function):
global $connection;
But you should be aware of the fact, that using globals is not a good idea and you may want to:
(preferably) pass $connection variable within the parameter of the function, or
move $connection declaration from outside the function just into the function (if it does not cause additional problems), or
redeclare $connection variable within the function (again: if it will not cause additional problems),
Because variables are local to functions. You need to add this inside your function:
global $connection;
Simply put, functions ignore outside variables due to variable scope. You must let the declare the variable as being from the outside by using global or you can send $connection through a parameter.

Function does not return correct resource

I have this function:
function query_dp($sql) {
$link = mysql_connect('localhost', $bd_id, $bd_pass);
mysql_select_db("$bd");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
return mysql_query($sql) or die(mysql_error());
mysql_close($link);
}
In the main program, when I try to do:
echo mysql_num_rows(query_db($sql));
I get as return
1
When I do not encapsulate that code in a function and use it directly to the main program, I get the number of rows fetched.
The function is not returning a Resource but an... integer? WTF?
Any help would be greatly appreciated!
Your variables $bd_id, $bd_pass and $bd are not visible inside the function since they are probably declared in the global scope and not the local scope of that function.
You would either make the global variables accessible by using the global keyword, by using the $GLOBALS variable, or by passing them to the function.
your call to mysql_close means that you no longer have a link to the mysql resource that you need in mysql_num_rows
The problem is in "or" operator. Your function returns result of "mysql_query($sql) or die(mysql_error())" expression, which is 1 or 0. I suggest you to use something like this:
$query_result = mysql_query($sql);
if (!$query_result) {
die(mysql_error());
}
return $query_result;
Also last line of this function "mysql_close($link)" is never called.
This doesn't directly answer your question, but you shouldn't use the original mysql interface. it is clunky and procedural. Take a look at the mysqli interface. Don't try to wrap the old functions if you have a language supported standard that already does this :D
You above code just becomes
$m = new MysqlI(...);
$rc = $m->query(...);
echo $rc->num_rows();

Categories