Search code examples
phpmysqlifwrite

How to have a mysqli stament inside an php fwrite


I am trying to make a new page using php fopen and fwrite. Inside the fwrite the code should be a mysqli statment for a simple page counter. The fwrite and fopen work and create a new page when there is just normal html(for example) it just doesnt work when I use a mysqli statment. Here is the error:

Catchable fatal error: Object of class mysqli could not 
be converted to string

And here is the code

$page = "

<?php

$con = new mysqli('localhost', 'mathswi3_data', '...',
'mathswi3_submits');

if ($mysqli->connect_error) {
die('Errr : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}


if (!mysqli_query($con, \"UPDATE submits SET views=views + 1 
WHERE url    = $nurl\"));
{
echo(\"Error description: \" . mysqli_error($con));
}
?>";

fwrite($fh, $page);
$filname = "tools/scripts/toolid.php";

fclose($fh);
exit();
?> 

The only error is the one stated above. Does anybody how to use a mysqli stament in a fwrite as it "cant be converted into a string..."


Solution

  • The feature you're getting blindsided by here is called string interpolation.

    $foo = "test";
    $bar = "this is a $foo";
    
    var_dump($bar); // "this is a test"
    

    A string created with double quotes can have variables in it. Those variables will have their value inserted into the string in their place when the string is created.

    When you're creating $page, you're doing so with double quotes. Everything is fine until you get to $mysqli at which point, php tries to convert it to a string so that it can fit into this $page variable.

    You'll need to escape the dollar signs with a slash like so.

    <?php
    
    \$con = new mysqli('localhost', 'mathswi3_data', '...',
    'mathswi3_submits');
    
    if (\$mysqli->connect_error) {
    die('Errr : ('. \$mysqli->connect_errno .') '. \$mysqli->connect_error);
    }