iconMatrix
iconMatrix

Reputation: 183

PHP posting a variable in a variable using mysql

I need to use the number of the district to be the tail end of my variable. Example $publish_page_ADD THE DISTRICT NUMBER I am grabbing the $district_num from my url which I've verified with echo

Here is what I've tried

$district_num = $_REQUEST['district_num']; // from url and works

$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work

$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work

$sql = "UPDATE districts SET
        publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list

        WHERE district_num ='$district_num'"; //this works when the above code is removed 

Follow up on corrected code... Thank You @cale_b and @Bill Karwin

     $district_num = (int) $_REQUEST['district_num']; 
     $$publish_page = "publish_page_{$district_num}";

     $$publish_page = $district_var[ "publish_page_{$district_num}"];

if (isset($_POST['submitok'])):
   $$publish_page = addslashes($_POST[$publish_page]);


    $sql = "UPDATE districts SET
            publish_page_{$district_num} = '$publish_page'

        WHERE district_num ='$district_num'";

Upvotes: 1

Views: 48

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562230

If you want to learn about PHP's variable variables, it's in the manual (I linked to it). But you actually don't need it in your case.

Be careful about SQL injection. Your code is vulnerable to it.

Since you're using input to form a SQL column name, you can't use SQL query parameters to solve it. But you can cast the input to an integer, which will protect against SQL injection in this case.

$district_num = (int) $_REQUEST['district_num'];

$publish_page_col = "publish_page_{$district_num}";

The above is safe because the (int) casting makes sure the num variable is only numeric. It isn't possible for it to contain any characters like ' or \ that could cause an SQL injection vulnerability.

For the other dynamic values, use query parameters.

$publish_page_value = $_REQUEST["publish_page_4{$district_num}"];

$sql = "UPDATE districts SET
        `$publish_page_col` = ?
        WHERE district_num = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([ $publish_page_value, $district_num ]);

As @cale_b comments below, you should understand that in PHP, variables can be expanded inside double-quoted strings. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details on that.

Upvotes: 2

Related Questions