Pulling settings from MySQL using Object-Orientated PHP - php

Ok, so I am slowly migrating from Procedural to OOP, and I'm finding it all pretty straight forward apart from one thing.
I used to use this method for pulling my settings data from a simple two-column settings table comprising of a row for each setting, defined with 'setting' and 'value' fields:
$query = mysql_query("SELECT * FROM `settings`");
while ($current_setting = mysql_fetch_array($query)) {
$setting[$current_setting['setting']] = $current_setting['value'];
}
As you can see, I manipulated it so that I could simply use $setting['any_setting_name'] to display the corresponding 'value' within that setting's row. I'm not sure if this is a silly way of doing things but no matter, I'm moving on anyway..
However, since moving to object orientated PHP, I don't really know how to do something similar..
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
echo $current_setting->setting; // echo's each setting name
echo $current_setting->value; // echo's each setting value
}
As you can see, I'm perfectly able to retrieve the data, but what I want is to be able to use it later on in the form of: $setting->setting_name; which will echo the VALUE from the row where setting is equal to 'setting_name'..
So basically if I have a row in my settings table where setting is 'site_url' and value is 'http://example.com/', I want $setting->site_url; to contain 'http://example.com/'.. Or something to the same effect..
Can anyone help me out here? I'm at a brick-wall right now.. Probably something really stupid I'm overlooking..

Since you are working with a resource it has a pointer. Once you get to the end you can't use it anymore. I think you can reset it but why not mix the new with the old?
I don't think you're going to have too much overhead, any that matters anyway, to do something like this:
$settings = array();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings[$current_setting->setting] = $current_setting->value;
}
Now you can use $settings as much as you want.
UPDATE
Haven't tested this or used it but are you looking to do something like this? Consider the following pseudo code and may not actually work.
$settings = new stdClass();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings->{$current_setting->setting} = $current_setting->value;
}

Related

Unreachable Statement in PHP

require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
return $SelectRowByIncrementQuery;
return $SelectedRow; //HERE is the error <-------------------------------
return $result;
}
$row = $SelectedRow;
echo $row;
if ($row['Id'] === max(mysqli_fetch_assoc($Id))){
$row['Id']=$row['Id'] === min(mysqli_fetch_assoc($Id));#TODO check === operator
}
else if($row['Id']=== min(mysqli_fetch_assoc($Id))){
$row['Id']=max(mysqli_fetch_assoc($Id));#TODO check === operator //This logic is important. DONT use = 1!
Ok, I am trying to write a program for the server end of my website using PHP. Using Netbeans as my IDE of choice I have encountered an error while attempting to write a function which will store a single row in an associative array.
The issue arises when I try to return the variable $SelectedRow. It causes an 'Unreachable Statment' warning. This results in the program falling flat on its face.
I can get this code to work without being contained in a function. However, I don't really feel that that is the way to go about solving my issues while I learn to write programs.
Side Notes:
This is the first question I have posted on SO, so constructive criticism and tips are much appreciated. I am happy to post any specifications that would help an answer or anything else of the sort.
I do not believe this is a so-called 'replica' question because I have failed to find another SO question addressing the same issue in PHP as of yet.
If anybody has any suggestions about my code, in general, I'd be stoked to hear, as I have only just started this whole CS thing.
You can only return one time. Everything after the first return is unreachable.
It's not entirely clear to me what you want to return from that function, but you can only return one value.
The return command cancels the rest of the function, as once you use it, it has served its purpose.
The key to this is to put all of your information in to an array and return it at the end of the function, that way you can access all of the information.
So try changing your code to this:
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
$returnArray = array();
$returnArray["SelectRowByIncrementQuery"] = $SelectRowByIncrementQuery;
$returnArray["SelectedRow"] = $SelectedRow;
$returnArray["result"] = $result;
return $returnArray;
}
And then you can access the information like so:
$selectedArray = SelectRowByIncrementFunc();
$row = $selectedArray["SelectedRow"]
And so forth...

Adding a secondary WHERE statement to PDO/MySql statement

I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.
The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();

While loop to gather data from database until array contains a certain value

I'm trying to create a while loop in PHP which retrieves data from a database and puts it into an array. This while loop should only work until the array its filling contains a certain value.
Is there a way to scan through the array and look for the value while the loop is still busy?
to put it bluntly;
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($sql)){
//Do stuff
//add it to the array
while($array !=) //<-- I need to check the array here
}
You can use in_array function and break statement to check if value is in array and then stop looping.
First off, I think it'd be easier to check what you're filling the array with instead of checking the array itself. As the filled array grows, searching it will take longer and longer. Insted, consider:
$array = array_merge($array, $row);
if (in_array('ThisisWhatIneed', $row)
{
break;//leaves the while-loop
}
However, if you're query is returning more data, consider changing it to return what you need, only process the data that needs to be processed, otherwise, you might as well end up with code that does something like:
$stmt = $db->query('SELECT * FROM tbl');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if ($row['dataField'] === 'username')
{
$user = $row;
break;
}
}
WHERE could help a lot here, don't you think? As well taking advantage of MySQL's specific SELECT syntax, as in SELECT fields, you, need FROM table, which is more efficient.
You may also have noticed that the code above uses PDO, not mysql_*. Why? Simply because the mysql_* extension Is deprecated and should not be used anymore
Read what the red-warning-boxes tell you on every mysql* page. They're not just there to add some colour, and to liven things up. They are genuine wanrings.
Why don't you just check each value when it gets inserted into the array? It is much more efficient than iterating over the whole array each time you want to check.
$array = array();
$stopValue = ...
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($sql)){
array_push($array,$row['column']);
if($row['column'] == $stopValue){
// The array now contains the stop value
break;
}

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

store mysql results in SESSION array for later use (to check via in_array)

I currently have this :
require_once('auth.php');
auth.php:
session_start();
if(!isset($_SESSION['SESS_MERCHANT_ID']) || (trim($_SESSION['SESS_MERCHANT_ID']) == '')) {
header("location: login-form.php");
exit();
}
mybadges.php:
$mybadges = mysql_query("SELECT badge_id
FROM badges WHERE merchant_id = $current_userid ORDER BY badge_id DESC");
while ($result = mysql_fetch_array($mybadges)){
$badge_id = $result['badge_id'];
}
I wanted to know how I can store $result['badge_id']; in a $_SESSION array (like $_SESSION['badges']?)
a more sensible version of 'auth.php'
session_start();
if(empty($_SESSION['SESS_MERCHANT_ID'])) {
header("location: login-form.php");
exit();
}
a more sensible version of mybadges.php:
$sql = "SELECT badge_id FROM badges WHERE merchant_id = $current_userid ORDER BY badge_id DESC"
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
in case there is only one bagde_id to store:
$row = mysql_fetch_array($res);
$_SESSION['badge'] = $row['badge_id'];
in case there are many id's (as one cannot say for sure from your code, what you need):
$badges = array();
while ($row = mysql_fetch_array($res)) {
$badge_ids[] = $row['badge_id'];
}
$_SESSION['badges'] = $badge_ids;
in general, to store anything an a session, just assign that anything to a session variable:
$_SESSION['badges'] = $badge_ids;
not a big deal.
a SESSION array become exectly what you wrote. $_SESSION['badges'] is a regular variable to use.
Note that you can save only scalars, arrays and objects. Not resources.
If I understand well your needs, you can simply do this :
$_SESSION['badges'] = $result['badge_id'];
Make sure that mybadges.php includes auth.php otherwise you won't have a session started. I'm assuming that's what you have but it doesn't show up that way in the code above. Assuming you have auth.php included, just do as sputnick said with
$_SESSION['badges'] = $result['badge_id'];
php sessions support multiple dimesion arrays.
$members=array();
foreach(mysql_fetch_array($memberresultset) as $key->$value)
$members[]=$value;
foreach($members as $mv)
$_SESSION["MEMBER"][]=$mv;
would work, for example.
Also something like this:
$_SESSION["badgeidnumbers"][]=$result["badgeid"]
But your would need to add them with foreach command, fetching more than one rows.
Extra brackets are for adding to the array using the new index number. you can write anything in the second brackets.
you also use some format like
$_SESSION["badgeidnumbers"][$result["badgeid"]]=$result["badgename"]
I do not recommend dividing your project into too many files. Normally, you shouldn't need session variables. Don't hesitate to ask ideas about the general structure of your application. It may save you a lot of time.

Categories