dcsimg
www.webdeveloper.com
Results 1 to 13 of 13

Thread: Please correct mistakes in code (converting MySQL functions into MySQLi ones)

  1. #1
    Join Date
    Nov 2017
    Posts
    17

    Please correct mistakes in code (converting MySQL functions into MySQLi ones)

    This thread continues from the closed thread "I Need help with converting mysql_ ..." I was going to post the following codes but the thread was closed. I've been trying to replace all mysql functions with mysqli ones in an old script which generates pages with reviews from users.

    First, I changed code in my functions.php file to establish connection to a database.

    Initial code:

    PHP Code:
    <?php

    $NumReviews 
    8;

    $db_name "xxxxxxxxxxxxxxxxx";

    $connection = @mysql_connect("xxxxxxxxx""xxxxxxxxxxxx""xxxxxxxxxxxx")

        or die(
    "Couldn't connect.");

    $db = @mysql_select_db($db_name$connection)

        or die(
    "Couldn't select database.");

    function 
    db_errno($args=array()) {

        return @
    mysql_errno();

    }
    function 
    db_error($args=array()) {

        return @
    mysql_error();

    }
    ?>
    Modified code:

    PHP Code:
    <?php
    class DB

    {
    static 
    $link;
    static 
    $dbname;
            public static function 
    connect()
            {
                    if(empty(
    self::$link))
                    {
                      
    $dbhost 'xxxxxxxxx';
                      
    $dbuser 'xxxxxxxx';
                      
    $dbpassword 'xxxxxxxxxxxxx';
                      
    $dbname 'xxxxxxxxxxxx';

                            
    self::$link = @mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
                            
    self::$dbname=$dbname;
                            
    mysqli_set_charset(self::$link'utf8');
                            or die(
    "Couldn't connect.");
                    }
            }
    }
    DB::connect();
    ?>
    Then, I converted mysql functions in admin_menu.php

    Initial code:

    PHP Code:
    <?php
    //if a session does not yet exist for this user, start one
    session_start();

    //if there is no username or password entered and the user has not already been validated, send user back to login page.
    if ((empty($_POST["admin_username"]) || empty($_POST["admin_passtext"])) && empty($_SESSION['valid_user']))
                {
                
    Header("Location: index.php");
                }

    include (
    "../body_edit.php");
    include (
    "../config.php");
    include (
    "../functions.php");

    //make sure user has been logged in.
    if (empty($_SESSION['valid_user']))
        {
        
    // User not logged in, check database
    //Check to see that the username and Password entered have admin access.
    $sqlaccess "SELECT username, passtext
            FROM admin 
            WHERE username='" 
    mysql_escape_string($_POST['admin_username']) . "' 
            AND passtext = '" 
    mysql_escape_string($_POST['admin_passtext']) . "'
            LIMIT 1
            "
    ;

        
    $resultaccess mysql_query($sqlaccess)
        or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $numaccess mysql_numrows($resultaccess);

        if (
    $numaccess == 0) {
    BodyHeader("Access Not Allowed!");
    ?>

    <P>To access the Administration area you need to have approved access. The username and Password (<?php echo "$admin_username and $admin_passtext"?>) you entered are not approved!<br>
      <a href="index.php">Please try again</a>
      <?php
    BodyFooter
    ();  
    exit;
    }
    // if numaccess

    //if the user/pass were valid create a session for the user.
    $_SESSION['admin_passtext'] = $_POST['admin_passtext'];
    $_SESSION['admin_username'] = $_POST['admin_username'];

    //since user has been verified, set a session for checking on admin pages.
    $_SESSION['valid_user'] = $_POST['admin_username'];

    //set cookie so admin can save login info if logout link is not clicked.
    if (empty($_COOKIE['admin_username']) && empty($_COOKIE['admin_passtext'])) {
    setcookie("admin_username"$_POST['admin_username'], time() + 31536000"/"); 
    setcookie("admin_passtext"$_POST['admin_passtext'], time() + 31536000"/");
    }
    //if cookie
        
    }//if session

    BodyHeader("$sitename Administration Menu"); 
                  
    //Get the number of reviews that are not approved.
            
    $result mysql_query("SELECT COUNT(*) as total FROM review WHERE approve='n'
            AND
            review_item_id != '0'"

            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysql_fetch_array($result);

        
    $total $rows["total"];

    //Get the total number of reviews that are approved.
            
    $result mysql_query("SELECT COUNT(*) as totaly FROM review WHERE approve='y'"
            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysql_fetch_array($result);
        
    $totaly $rows["totaly"];    
        
        
    //Get the total number of user submitted items that need to be approved.
            
    $result mysql_query("SELECT COUNT(*) as totalitemuser FROM review_items_user"
            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysql_fetch_array($result);
        
    $totalitemuser $rows["totalitemuser"];    

            
    ?>

    //some code here....


    <?php
            BodyFooter
    (); 
            exit;
    ?>
    Modified code:


    PHP Code:
    <?php
    //if a session does not yet exist for this user, start one
    session_start();

    //if there is no username or password entered and the user has not already been validated, send user back to login page.
    if ((empty($_POST["admin_username"]) || empty($_POST["admin_passtext"])) && empty($_SESSION['valid_user']))
                {
                
    Header("Location: index.php");
                }

    include (
    "../body_edit.php");
    include (
    "../config.php");
    include (
    "../functions.php");

    //make sure user has been logged in.
    if (empty($_SESSION['valid_user']))
        {
        
    // User not logged in, check database
    //Check to see that the username and Password entered have admin access.
    $sqlaccess "SELECT username, passtext
            FROM admin
            WHERE username='" 
    mysqli_real_escape_string($_POST['admin_username']) . "'
            AND passtext = '" 
    mysqli_real_escape_string($_POST['admin_passtext']) . "'
            LIMIT 1
            "
    ;

        
    $resultaccess mysqli_query(db::$link,$sqlaccess)
        or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $numaccess mysqli_numrows($resultaccess);

        if (
    $numaccess == 0) {
    BodyHeader("Access Not Allowed!");
    ?>

    //some code here...

    <P>To access the Administration area you need to have approved access. The username and Password (<?php echo "$admin_username and $admin_passtext"?>) you entered are not approved!<br>
      <a href="index.php">Please try again</a>
      <?php
    BodyFooter
    ();
    exit;
    }

    // if numaccess

    //if the user/pass were valid create a session for the user.
    $_SESSION['admin_passtext'] = $_POST['admin_passtext'];
    $_SESSION['admin_username'] = $_POST['admin_username'];

    //since user has been verified, set a session for checking on admin pages.
    $_SESSION['valid_user'] = $_POST['admin_username'];

    //set cookie so admin can save login info if logout link is not clicked.
    if (empty($_COOKIE['admin_username']) && empty($_COOKIE['admin_passtext'])) {
    setcookie("admin_username"$_POST['admin_username'], time() + 31536000"/");
    setcookie("admin_passtext"$_POST['admin_passtext'], time() + 31536000"/");
    }
    //if cookie
        
    }//if session

    BodyHeader("$sitename Administration Menu");

    //Get the number of reviews that are not approved.
            
    $result mysqli_query(db::$link,"SELECT COUNT(*) as total FROM review WHERE approve='n'
            AND
            review_item_id != '0'"
    )
            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysqli_fetch_array($result);

        
    $total $rows["total"];

    //Get the total number of reviews that are approved.
            
    $result mysqli_query(db::$link,"SELECT COUNT(*) as totaly FROM review WHERE approve='y'")
            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysqli_fetch_array($result);
        
    $totaly $rows["totaly"];

        
    //Get the total number of user submitted items that need to be approved.
            
    $result mysqli_query(db::$link,"SELECT COUNT(*) as totalitemuser FROM review_items_user")
            or die(
    sprintf("Couldn't execute sql_count, %s: %s"db_errno(), db_error()));

        
    $rows mysqli_fetch_array($result);
        
    $totalitemuser $rows["totalitemuser"];

            
    ?>

          //some code here...

          <?php
                  BodyFooter
    ();
                  exit;
          
    ?>
    Could you please correct any mistake you see in these code snippets? I don't consider myself knowledgeable in php so your explanations will be appreciated! Thank you!

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    You can help us help you by actually testing it and letting us know what errors you get. To that end, for now it may be beneficial to make sure each main PHP script starts with the following:
    PHP Code:
    <?php
    error_reporting
    (E_ALL);
    ini_set('display_errors'true); // set to false in production
    This should ensure you have some (hopefully) useful error messages to share with us wherever things break.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  3. #3
    Join Date
    Nov 2017
    Posts
    17
    Quote Originally Posted by NogDog View Post
    You can help us help you by actually testing it and letting us know what errors you get...
    Dear NogDog,

    After using the PHP Code Checker I got this error notices:

    1) for code in functions.php file:

    PHP Syntax Check: Parse error: syntax error, unexpected 'or' (T_LOGICAL_OR) in your code on line 19
    or die("Couldn't connect.");

    2) for code in admin_menu.php file:

    Error: There is 1 more closing parenthesis ')' found
    This count is unaware if parenthesis are inside of a string

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    If you just want to die() when you don't connect like that, then the "or... needs to be part of the connection attempt:
    PHP Code:
    <?php
    class DB
    {
        static 
    $link;
        static 
    $dbname;
        public static function 
    connect()
        {
            if(empty(
    self::$link))
            {
                
    $dbhost 'xxxxxxxxx';
                
    $dbuser 'xxxxxxxx';
                
    $dbpassword 'xxxxxxxxxxxxx';
                
    $dbname 'xxxxxxxxxxxx';

                
    self::$link = @mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname)
                    or die(
    "Couldn't connect.");
                
    self::$dbname=$dbname;
                
    mysqli_set_charset(self::$link'utf8');
            }
        }
    }
    DB::connect();

    // there's no need for a closing php tag in this case, so it's often better to leave it out
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  5. #5
    Join Date
    Nov 2017
    Posts
    17
    NodDog, thank you very much for correcting the mistake! You wrote: "there's no need for a closing php tag in this case, so it's often better to leave it out". That code snippet with connection to a DB is actually the only code in my functions.php file, so I thought there must be a closing php tag?

  6. #6
    Join Date
    Nov 2017
    Posts
    17
    NodDog, I'm wondering if I could go without "or die("Couldn't connect.")"? Or should I insert another line such as "or die("Couldn't select database.")" which is present in my initial code of functions.php file here (not to refer you back to the thread's top):
    PHP Code:
    <?
    //Choose how many reviews per page to display
    $NumReviews 8;

    //Set the name of the Table, Database, Username and Password for Mysql.
    $db_name "*****";

    $connection = @mysql_connect("*****""*****""*****")

        or die(
    "Couldn't connect.");

    $db = @mysql_select_db($db_name$connection)

        or die(
    "Couldn't select database.");

    function 
    db_errno($args=array()) {

        return @
    mysql_errno();

    }
    function 
    db_error($args=array()) {

        return @
    mysql_error();

    }
    ?>
    In other words, should my new code be similar to the initial code except MySQL interface or can I exclude those lines along with mysql_errno and mysql_error? I would like to have my code similar to the initial, but is it necessary?
    Last edited by NogDog; 11-14-2017 at 09:52 AM. Reason: removed DB credentials

  7. #7
    Join Date
    Nov 2017
    Posts
    17
    Moderator, please delete my last post as I accidentally posted info which I shouldn't post.

  8. #8
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    Quote Originally Posted by visitor52 View Post
    Moderator, please delete my last post as I accidentally posted info which I shouldn't post.
    I just edited it to obfuscate the DB credentials.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  9. #9
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    Quote Originally Posted by visitor52 View Post
    NodDog, I'm wondering if I could go without "or die("Couldn't connect.")"? Or should I insert another line such as "or die("Couldn't select database.")" which is present in my initial code of functions.php file here (not to refer you back to the thread's top):
    PHP Code:
    <?
    //Choose how many reviews per page to display
    $NumReviews 8;

    //Set the name of the Table, Database, Username and Password for Mysql.
    $db_name "*****";

    $connection = @mysql_connect("*****""*****""*****")

        or die(
    "Couldn't connect.");

    $db = @mysql_select_db($db_name$connection)

        or die(
    "Couldn't select database.");

    function 
    db_errno($args=array()) {

        return @
    mysql_errno();

    }
    function 
    db_error($args=array()) {

        return @
    mysql_error();

    }
    ?>
    In other words, should my new code be similar to the initial code except MySQL interface or can I exclude those lines along with mysql_errno and mysql_error? I would like to have my code similar to the initial, but is it necessary?
    `or die('some message')` is very user-unfriendly, so in general I wouldn't recommend it. It's useful for debugging during development, but is pretty poor in a production environment. Better would be something where you test if the result is false, and if so, log the error info to the php error log and display some user-friendly message that there was a problem and the error has been logged, people notified, whatever makes sense for you...

    Along those lines, suppressing errors with the @ operator can be counter-productive to debugging production issues. Better would be to ensure that errors are not displayed in that environment with the 'display_erros' setting set to false:
    PHP Code:
    <?php
    ini_set
    ('display_errors'false);
    error_reporting(E_ALL); // all warnings/errors will be in PHP error log
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  10. #10
    Join Date
    Nov 2017
    Posts
    17
    Thank you, NodDog! I removed '@' and added "display errors" code. Going back to the "closing php tag" question, after removing the "or die ('Couldn't connect') from my code, the PHP code checker didn't show any errors even with the closing php tag. Now I ended up with this code in my functions.php file:

    PHP Code:
    <?php

    ini_set
    ('display_errors'false);
    error_reporting(E_ALL); // all warnings/errors will be in PHP error log

    class DB
    {
        static 
    $link;
        static 
    $dbname;
        public static function 
    connect()
        {
            if(empty(
    self::$link))
            {
                
    $dbhost 'xxxxxxxxx';
                
    $dbuser 'xxxxxxxx';
                
    $dbpassword 'xxxxxxxxxxxxx';
                
    $dbname 'xxxxxxxxxxxx';

                
    self::$link mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
                
    self::$dbname=$dbname;
                
    mysqli_set_charset(self::$link'utf8');
            }
        }
    }
    DB::connect();
    ?>
    But if I stick to the "or die ('some message')" option (unfortunately I'm not able to implement the option you suggested), where do I add those lines in my code above without getting the "error messages" from the PHP code checker?

  11. #11
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    Basically, anything that you think could possibly fail -- or would be a show-stopper if it ever did fail -- you can check the return value and react accordingly. So...
    PHP Code:
                self::$link mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
                if(
    self::$link == false) {
                    
    error_log("DB connection failed:".PHP_EOL.mysqli_connect_error());
                    
    // output whatever user-friendly message you want, then exit.
                    // or whatever else you want to do: maybe a generic error function?
                    
    exit;
                } 
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  12. #12
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    1,835
    And - while you are doing your development - you should set this to true so that you can SEE the errors instead of having to go view the log every time:

    Code:
    ini_set('display_errors', true);  // turn on errors while development
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  13. #13
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    22,214
    Quote Originally Posted by ginerjm View Post
    And - while you are doing your development - you should set this to true so that you can SEE the errors instead of having to go view the log every time:

    Code:
    ini_set('display_errors', true);  // turn on errors while development
    Or just tail -f /path/to/php_errors.log in a terminal window, if you know where the log file is. \_(ツ)_/
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center