using functions to simplify CMS theming - php

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.

Related

Select by id mysql php

I would like to select rows by id and show it. My Table is named text
And this is whats in the table
BookID Type init
Title
Author
PublisherName
CopyrightYeare
here is how i would like to call them
text id 10
by this action i get row nummber 10 and i get all the information in
BookID, Title, Author, PublisherName, CopyrightYeare
If I query this
text id 14
by this action i get row nummber 14 and i get all the information again.
<?php
function text($id){
$query = "SELECT * FROM text WHERE BookID =" .$id ;
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
}
?>
<?php
echo text (14) ;
?>
You have a few problems.
You are using the obsolete mysql_* functions. Consider upgrading to mysqli
You are vulnerable to SQL injection attacks. Again, look at mysqli and read up on how to use prepared statements correctly.
Your function is named text, you are calling displaytext
Your function is not returning a result. At the end of the function, add return $row; to get the results back
You are calling a function called displytext() but the function is called text().
The function text() does not return a value so the echo will have nothing to print.
Sorry for the late reply, just had another gander and here is a working code.
Problems wre
You did not return anything from your functions
You did not escape the $id which would leave it prone to SQL injection
The previously stated function name,
I hope this sorts it for you. See the code bellow
<?php
function text($id){
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM text WHERE BookID = $id";
$row = mysql_fetch_assoc(mysql_query($query));
return $row;
}
print_r(text('1'));
?>

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

php function save result at array

hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>

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.

PHP: call a string from another page function?

Can you do that? I just tried but it doesnt seem to work.
I have dbc.php included at top of my page, and in dbc.php at the bottom i created this function:
function getUserInfo($id) {
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$showUR = mysql_fetch_array($thaString);
$showURP = mysql_fetch_array($thaString2);
}
So it would be easier for me to call them instead of running the queries all the time when i need them in other pages..
But when i try to do:
getUserInfo($showInfo["bID"]);
echo $showUR["full_name"];
I dont get any result, is there a smarter way to do this, if so how?
It's an issue of scope: $showUR is set inside getUserInfo(), so it's not available to the echo outside the function. There are lots of potential modifications you could make, but you may want to assign your values into an array and then return that array:
function getUserInfo($id) {
$user = array();
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$user['showUR'] = mysql_fetch_array($thaString);
$user['showURP'] = mysql_fetch_array($thaString2);
return $user;
}
$user = getUserInfo($showInfo["bID"]);
echo $user['showUR']["full_name"];
Your functions have to return something for the values to be used, or $showUR and $showURP will just get lost once the function exits (ie: the scope will change). Something like:
function someFunc($arg) {
return "Hello, I am {$arg}";
}
$showUR = someFunc('name');
echo $showUR;
And please don't call stuff $thaString. First because it's a misnomer (mysql_query() doesn't return a string, it returns a resource or a boolean), Second because "tha" is so lame.
Let your function return the variable.
And then use $showUR = getUserInfo(...)
If you declare them outside the function, and then as globals inside the function you should be able to use them as you are now.

Categories