How to properly use mysqli_free_result function in PHP - php

I'm trying to use mysqli_free_result function in my website, to free results after they are used.
But it says:
Warning: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in
It might also be called before I use the result. I'd like to know how to properly use it
<?php
function find_all_subjects(){
global $connection;
$query = "SELECT * ";
$query .= "FROM blog_subject WHERE ID > 2";
$subject_set = mysqli_query($connection, $query);
mysqli_free_result($subject_set);
return $subject_set;
}
?>
I return value, and echo the function to display list of subjects.
Okay, if i have to use mysqli_free_result, after the return $subject_set,
Then i do i know that, the result is freed, if value has already been returned?

Do not use it.
function find_all_subjects($connection){
$query = "SELECT * FROM blog_subject WHERE ID > 2";
return $connection->query($query)->fetch_all();
}
I'm trying to use mysqli_free_result function in my website, to free results after they are used.
No need to do it. PHP will clean everything up automatically.

Related

Array_Rand always returns same value PHP fetch array

I have this function:
function set_spell() {
global $connection;
$query = "SELECT * FROM Spells";
$result_set = mysqli_query($connection, $query);
$spell_id_list = mysqli_fetch_array($result_set);
return $spell_id_list;
Then I try to output a random ID from the array, but I always get ID 1.
$spell_id_list = set_spell();
echo $spell_id_list[array_rand($spell_id_list)];
When I run this query in MYSQL, I get a list of all ID's as expected. Why doesn't the code above select one at random?
This is probably a stupid questions that I'll smack myself after I see the answer... but I've been stuck for longer than I think I should be on it.
Thanks for the help.
You just returning only single result from your function so either create array of all fetched results & return the same, or simply use order by rand() in your query,
SELECT * FROM Spells ORDER BY RAND();

Generic MySQL Select All Function

I write a lot of SELECT * FROM... kind of queries in my web sites. I'd like to write a function that looks after this for me so I can call on it more quickly, without using more advanced techniques like PDO and OOP. Im just confused on how I would call the data I retrieve from the database, particularly when looping through the array's results.
I'd love something like this:
function selectAll($tableName, $limitAmount) {
global $dbConnection;
$query = mysql_query("SELECT * FROM $tableName ORDER BY id LIMIT $limitAmount");
$row_result = mysql_fetch_assoc($query);
return $row_result;
}
Say it was a bunch of news posts. Id like to loop through the results in one of the typical ways:
// CALL THE FUNCTION
selectAll('news_table', '10');
// SOMEHOW LOOP THROUGH RESULTS??
do {
echo "<h2>".$row_result['title']."</h2>";
} while ($row_result = mysql_fetch_assoc($query));
Obviously this isn't how I loop through the bespoke results of a function. Im not even sure if my function is correct.
Any help is greatly appreciated.
EDIT: Forgot to return a result inside the function and call the actual function. My bad. Updated now.
There is no point in having such a function called like yours.
Just make it like this
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and use it with whatever query:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
An SQL query being a powerful program itself. Do not reduce it's power to silly selects.
Use SQL to represent data processing logic and this helper function to avoid repetitions.

Web browser is returning nothing - function error?

When I access this from a web browser it returns nothing other than echo'd text, I know this is similar to another question I posted but I can't make sense of it?
<?php
include('config.php');
include('database.php');
class conversion{
public $amnt;
public $cc_from;
public $cc_to;
public function __construct (){
$this->amnt = htmlspecialchars($_GET["amnt"]);
$this->cc_from = htmlspecialchars($_GET["from"]);
$this->cc_to = htmlspecialchars($_GET["to"]);
}
function convert($this->amnt,$this->cc_from,$this-cc_to,$decimals=2){
$db_rate_from = mysql_query("SELECT * FROM _currency WHERE country_code='$this- >cc_from'") or die(mysql_error());;
$query_row_from = mysql_fetch_array($db_rate_from);
$rate_from = ($query_row_from['rate']);
echo $rate_from;
echo "</br>rate to</br>";
$db_rate_to = mysql_query("SELECT * FROM _currency WHERE country_code='$this->cc_to'") or die(mysql_error());;
$query_row_to = mysql_fetch_array($db_rate_to);
$rate_to = ($query_row_to['rate']);
echo $rate_to;
echo "</br>conversion</>";
$conversion = (number_format(($amnt/$rate_from)*$rate_to,$decimals));
echo $conversion;
} }
$var = new conversion();
$var->convert($amnt,$cc_from,$cc_to);
?>
Given this:
$db_rate_from = mysql_query("SELECT * FROM $db_tbprefix WHERE country_code='$this->cc_from'");
where is $db_tbprefix defined? Nowhere, causing your query to be SELECT * FROM WHERE .... If you had proper SQL error handling code, this would've been clear to you. At absolute bare minimum, you should have something like:
$result = mysql_query("...") or die(mysql_error());
which would abort the script on a query failure and tell you exactly why the query failed.
As well, htmlspecialchars is NOT intended for database operations. It does absolutely nothing to prevent SQL injection. For that, you have to use mysql_real_escape_string().
One thing I notice is that you call your method without parameters.
$var->convert();
Yet it is declared to take three mandatory parameters.
function convert($amnt,$cc_from,$cc_to,$decimals=2)
And btw, don't use $query_row_to[rate]. Use either $query_row_to['rate'] or $query_row_to[$rate].
Edit:
How about something like this? Use global $db_tbprefix and skip object orientation.
<?php
include('config.php');
include('database.php');
function convert($amnt,$cc_from,$cc_to,$decimals=2) {
global $db_tbprefix;
$db_rate_from = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_from'") or die mysql_error();
$query_row_from = mysql_fetch_assoc($db_rate_from);
$rate_from = $query_row_from['rate'];
$db_rate_to = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_to'") or die mysql_error();
$query_row_to = mysql_fetch_assoc($db_rate_to);
$rate_to = $query_row_to['rate'];
return number_format(($amnt/$rate_from)*$rate_to,$decimals);
}
echo convert(floatval($_GET["amnt"]), mysql_real_escape_string($_GET["from"]), mysql_real_escape_string($_GET["to"]));
?>
Edit 2: only select what you need, in this case rate. And use mysql_fetch_assoc rather than than mysql_fetch_array which will double your memory consumption and slow down your code.
haven' tested it ... but the possibility i can find is you are passing parameters in function convert while defining it so you need to pass the same param while calling it... OR if the variables are the reference from the predefined one then use them like this
function convert($this->amnt,$this->cc_from,$this->cc_to,$decimals=2){
}

PHP Variable - Multiply pages

I have a functions.php page, I have included in ALL my other php pages. What I want is a function in my functions.php page, I can use in all the other pages.
I have tried this:
function getSetting()
{
$r=mysql_query("SELECT * FROM settings");
if(mysql_num_rows($r) == 0)
return false;
else
$sdata=mysql_fetch_assoc($r);
return $sdata;
}
The thing I want to, I want to get the data from the row next to the name in the following picture: http://awesomescreenshot.com/0bci8x472
Example:
If I write $sdata['sitename'], I want it to output "ptcify"
Thanks!
Try using mysql_fetch_array() with MYSQL_ASSOC as documented at this link http://www.php.net/manual/en/function.mysql-fetch-array.php.
There are a lot of things you could do to further improve your code implementation i.e OOP, using better database abstraction libraries(even switching to PDO insted of PHP_MYSQL is an improvement), but this should work straight of the bat.
Most questions usually have a ? in them somewhere, to indicate an actual question. I'm not sure what the problem with your code is, but I'm guessing you're only getting a single "setting" result - if that query returns multiple rows, you have to loop over the result set and get each row, THEN return:
$r = mysql_query(...) or die(mysql_error());
$sdata = array()
while ($row = mysql_fetch_assoc($r)) {
$sdata[] = $row;
}
return $sdata
edit
$sql = "SELECT setting_name, setting_value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
$sdata = array();
while($row = mysql_fetch_assoc($result)) {
$sdata[$row['setting_name']] = $row['setting_value'];
}
return $sdata;

using functions to simplify CMS theming

I'm in the process of making my own CMS. I have some code that selects database rows to be echoed out on the page like so:
$query = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
However whenever I try to put this inside a function and call the function instead of using that long lines of code, nothing happens. Am I missing something with PHP functions?
function posts() {
mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
while($row = mysql_fetch_array(posts())) {
$id = $row['id'];
echo $id;
}
You need to return the result:
function posts() {
return mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
Without seeing your function code, it's impossible to say what the problem is, but if I had to guess based on your description, the first thing I'd check is to see if you are (a) returning $query in your function and (b) assigning the return value to something else in your calling code.
UPDATE: So, based on the code you posetd, yes, the problem is (a) above--you need to return the value. Just put "return" before the rest of the one line of code in the function and it should work.

Categories