PHP Variable - Multiply pages - php

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;

Related

How to use phpspellcheck with sql

I am trying to use an array with phpspellcheck but it seems like it is not picking up anything from the array that I have created from mysql. It works just fine with an array I manually created. Is there any suggestions? I could easily use a text file but it takes so much time to load since there are 40,000+ words I need to add to the dictionary.
Here's my function
public function get_new_words(){
$sql = "SELECT field FROM table";
$result = mysql_query($sql) or die(mysql_error());
$words = array();
while($row = mysql_fetch_assoc($result)){
$words[] = $row['field'];
}
return $words;
}
Here is how I call the function for the phpspellcheck
$getWords = get_new_words();
/* other script to make spell check run is here */
$spellcheckObject ->AddCustomDictionaryFromArray($getWords);
Thank you

How do I optimize these two lines?

So, I have these two lines of PHP.
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db));
$total_row_count = $total_row_count['count'];`
Is there any way to change the first declaration of $total_row_count so the 2nd line isn't necessary?
Something to this effect (I know this isn't functional code).
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db))['count'];
Thanks so much!
You second snippet is perfectly functional since PHP 5.4. It's called direct array dereferencing.
However, you should never ever do mysql_fetch_assoc(mysql_query(...)). The mysql_query call may fail and return false, which propagates ugly errors into mysql_fetch_assoc. You need error handling!
$result = mysql_query(...);
if (!$result) {
die(mysql_error());
// or
return false;
// or
throw new Exception(mysql_error());
// or whatever other error handling strategy you have
}
$row = mysql_fetch_assoc($result);
$count = $row['count'];
If this is too much code for you to repeat often, wrap it in a function.
function getCount() {
$result = mysql_query(...);
...
return $row['count'];
}

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']);
?>

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

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.

Categories