Skip to content
Advertisement

Old PHP project undeclared variables to PHP 7

I’m trying to update an old PHP project and I’m not really aware of PHP 4 and 5. I don’t fully understand what is going on in the snippet below..

$page_num isn’t declared anywhere and I get Notice: Undefined variable: page_num. There’s a lot of undefined variables in the code and multiple uses of mysql_result which is not supported in PHP 7.

PHP snippet:

if ($page_num) {
    $getpage_IDquery = MYSQL_QUERY("SELECT page_ID FROM pages WHERE ID='$ID' AND page_num='$page_num' ORDER BY page_ID");
    if (mysql_num_rows($getpage_IDquery) > 0) {
        $page_ID = MYSQL_RESULT($getpage_IDquery,0,"page_ID");
    }
}

In the query (SELECT page_ID FROM pages WHERE ID='$ID' AND page_num='$page_num' ORDER BY page_ID) there are $ID and $page_num which, also, aren’t defined anywhere in the code – not sure what is to be accomplished with it..

Table:

'pages' > ID, page_ID, picture, page_num;

Can anyone help me update the snippet to PHP7 using mysqli? What is mysql_result alternative?

Advertisement

Answer

You are using the variable $page_num in the if condition, but it seems to be never have been declared or initialized before. It is not the query producing the error, it is the if-statement.

I’ve altered the code to use PDO. You need to create the connection, first.

$pdo = new PDO('mysql:host=localhost;dbname=db', $username, $password, $options);

You could add additional validation in the condition by doing

if (!empty($page_num) && $page_num > 0) {
    $sth = $pdo->prepare("SELECT page_ID FROM pages WHERE ID=? AND page_num=? ORDER BY page_ID");
    $sth->execute([$ID, $page_num]);
    $page_ID = 0;
    if($sth->rowCount()) {
        $row = $sth->fetchObject();
        if ($row) $page_ID = $row->page_ID;
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement