Syarif Mathis
Syarif Mathis

Reputation: 161

How to link variable and strings in PHP

I have a table called cms_settings. I name all the tabels with a prefix cms_ so i created a variable $dbpraefix="cms_" when i call the entry using "select value from $dbpraefix.settings" command, it failed to proceed.

i also tried defferent version. like "select from '.$dbpraefix.'settings etc. nothing works.

but if i use "select value from cms_settings instead, it works!. how can i fix this. thanks a lot

 <?PHP
    function getSetting($property){
    global $connection;
    $dbpraefix= "cms_";
    $sql= "SELECT value FROM $dbpraefix.settings WHERE property='$property'";
    $ergebnis= mysqli_query($connection, $sql);
    $row = mysqli_fetch_row($ergebnis);
    return $row[0];
    }
?>

Upvotes: 0

Views: 79

Answers (4)

Aswathy
Aswathy

Reputation: 211

change your query as below

$sql= "SELECT value FROM ".$dbpraefix."settings WHERE property='$property'";

Upvotes: 0

Olajide Eniseyin
Olajide Eniseyin

Reputation: 1

The easiest way is to add a new parameter to your function so that when pass into the function it specify the table's name Eg : $table = "settings";

function getSetting($property,$table){
global $connection;
$table= "cms_".$table;
$sql= "SELECT value FROM $table WHERE property='$property'";
$ergebnis= mysqli_query($connection, $sql);
$row = mysqli_fetch_row($ergebnis);
return $row[0];
}

Upvotes: 0

BeetleJuice
BeetleJuice

Reputation: 40946

Your query fails because in the string "...$dbapraefix.settings..." PHP doesn't realize that you want the . in the middle to be the string concatenation operator instead of a simple dot. As a result the string becomes cms_.settings instead of cms_settings

Change:

"SELECT value FROM $dbpraefix.settings WHERE property='$property'";

To

"SELECT value FROM {$dbpraefix}settings WHERE property='$property'";

Upvotes: 3

MarcHoH
MarcHoH

Reputation: 340

You have a dot between the prefix and table name, that's why it won't work.

Try this: " . $dbpraefix . "settings.

Upvotes: 0

Related Questions