Error updating PHP script to new version (Mysqli)

Asked

Viewed 126 times

0

This script is used together with Coppermine Gallery to show the last albums created in the gallery. However, it does not seem to work with PHP 7. When strings are kept in the old format (mysql_connect), the error given is as follows:

Fatal error: Uncaught Error: Call to Undefined Function mysql_connect() in /home/gustavoj/public_html/lauramarano.com.br/galeria/api.php:8 Stack trace: 0 {main} thrown in /home/gustavoj/public_html/lauramarano.com.br/galeria/api.php online 8

And when changed to mysqli_connect, here is the error:

Warning: mysqli_select_db() expects Parameter 1 to be mysqli, string Given in /home/gustavoj/public_html/lauramarano.com.br/galeria/api.php online 10
Error connecting to database

My question is, what is the best way to update this script. And if there is a way to update this script, because it is amazing and helps a lot in front-end development. Follow the code of the script.

<?php
require_once('include/config.inc.php');
header("Content-type: application/x-javascript");



$connect = mysqli_connect($CONFIG['dbserver'],$CONFIG['dbuser'],$CONFIG['dbpass'])
    or die('Erro ao conectar ao servidor');
$connect_db = mysqli_select_db($CONFIG['dbname'], $connect)
    or die ('Erro ao conectar ao banco de dados');


            $resultado = mysqli_query("SELECT * FROM `cpg_albums` ORDER BY `cpg_albums`.`aid` DESC LIMIT 0 , 12", $link)

                or die('Nenhum album encontrado com esta query');

                echo 'document.write(\'';

                if(mysqli_num_rows($resultado) == 0){
                    echo 'Nenhum álbum cadastrado';
                } else { echo '<div id="postsgall">  ';
                    while($row = mysqli_fetch_array($resultado)){
                        echo ' ';
                            $album_id = $row['aid'];
                            $subresult = mysqli_query("SELECT * FROM `cpg_pictures` where aid=$album_id order by pid DESC LIMIT 0, 20");

                            if(mysqli_num_rows($subresult) == 0){
                                $album_img = "http://lauramarano.com.br/galeria/images/thumbs/thumb_nopic.png";
                            } else {
                                while($subrow = mysqli_fetch_array($subresult)){
                                    $album_img = "http://lauramarano.com.br/galeria/albums/".$subrow['filepath'].'normal_'.$subrow['filename']  .$subrow['datebrowse'];

                                }
                            }

                            echo '<div><div class="postsg1"><div class="title">'.$row['title'].' </div><a href="http://lauramarano.com.br/galeria/thumbnails.php?album='.$album_id.' "><img src="http://lauramarano.com.br/wp-content/themes/lmbr16/timthumb.php?src='.$album_img.'&w=164&h=223&zc=1" alt="" /></a> </div></div>';  

                        echo '';
                    }
                } echo '</tr></div>';
                echo '\');';

        ?>

1 answer

0


Why not consider using PDO? Pdo would be one of the best options for PHP database, it is object-oriented and has several security options. At a glance: http://php.net/manual/en/class.pdo.php

Now answering your question has several errors there, it is not simply changing from mysql to mysqli and all functions will work... There are some restrictions, I will be leaving comments of improvements and repairs. I ask you to indent your code also to make it easier next time, if you’re not going to bat your eye or want to analyze.

<?php
require_once('include/config.inc.php');
header("Content-type: application/x-javascript");


//Você já pode passar a db direto aqui
$connect = mysqli_connect($CONFIG['dbserver'], $CONFIG['dbuser'], $CONFIG['dbpass'], $CONFIG['dbname']);

if (mysqli_connect_errno()) {
    echo "Falha ao conectar: " . mysqli_connect_error();
}
//Na execução da query é necessário passar a conexão como primeiro parametro
$resultado = mysqli_query($connect, "SELECT * FROM `cpg_albums` ORDER BY `cpg_albums`.`aid` DESC LIMIT 0 , 12");

echo 'document.write(\'';

if (mysqli_num_rows($resultado) == 0) {
    echo 'Nenhum álbum cadastrado';
} else {
    echo '<div id="postsgall">  ';
    while ($row = mysqli_fetch_array($resultado)) {
        echo ' ';
        $album_id  = $row['aid'];
        $subresult = mysqli_query($connect, "SELECT * FROM `cpg_pictures` where aid=$album_id order by pid DESC LIMIT 0, 20");

        if (mysqli_num_rows($subresult) == 0) {
            $album_img = "http://lauramarano.com.br/galeria/images/thumbs/thumb_nopic.png";
        } else {
            while ($subrow = mysqli_fetch_array($subresult)) {
                $album_img = "http://lauramarano.com.br/galeria/albums/" . $subrow['filepath'] . 'normal_' . $subrow['filename'] . $subrow['datebrowse'];

            }
        }

        echo '<div><div class="postsg1"><div class="title">' . $row['title'] . ' </div><a href="http://lauramarano.com.br/galeria/thumbnails.php?album=' . $album_id . ' "><img src="http://lauramarano.com.br/wp-content/themes/lmbr16/timthumb.php?src=' . $album_img . '&w=164&h=223&zc=1" alt="" /></a> </div></div>';

        echo '';
    }
}
echo '</tr></div>';
echo '\');';

?>

I will also be leaving the method with PDO if you want to use

<?php
    try{
        $conn = new PDO("mysql:host=$CONFIG['dbserver'];dbname=$CONFIG['dbname']", $CONFIG['dbuser'], $CONFIG['dbpass']);
        //Seta o modo do erro do PDO para excessão
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $data = $conn->query("SELECT * FROM `cpg_albums` ORDER BY `cpg_albums`.`aid` DESC LIMIT 0 , 12")->fetchAll(PDO::FETCH_ASSOC);

        echo 'document.write(\'';

        if (count($data) == 0) {
            echo 'Nenhum álbum cadastrado';
        } else {
            echo '<div id="postsgall">  ';
            while ($data as $row) {
                echo ' ';
                $album_id  = $row['aid'];
                $subresult = $conn->query("SELECT * FROM `cpg_pictures` where aid=$album_id order by pid DESC LIMIT 0, 20")->fetchAll(PDO::FETCH_ASSOC);

                if (count($subresult) == 0) {
                    $album_img = "http://lauramarano.com.br/galeria/images/thumbs/thumb_nopic.png";
                } else {
                    while ($subresult as $subrow) {
                        $album_img = "http://lauramarano.com.br/galeria/albums/" . $subrow['filepath'] . 'normal_' . $subrow['filename'] . $subrow['datebrowse'];

                    }
                }

                echo '<div><div class="postsg1"><div class="title">' . $row['title'] . ' </div><a href="http://lauramarano.com.br/galeria/thumbnails.php?album=' . $album_id . ' "><img src="http://lauramarano.com.br/wp-content/themes/lmbr16/timthumb.php?src=' . $album_img . '&w=164&h=223&zc=1" alt="" /></a> </div></div>';

                echo '';
            }
        }
        echo '</tr></div>';
        echo '\');';



    }
    catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
?>
  • I kept the old code, because in yours he couldn’t get to the pictures. So I used the way you called db, but I used the old code to call up the images. Just add a $connect before specifying the item name inside the db, and voila! (If you want to see the script working, see here https://bit.ly/2MNxC2k). Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.