/    Sign up×
Community /Pin to ProfileBookmark

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:

[code=php]
<?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();

}
?>
[/code]

Modified code:

[code=php]
<?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();
?>

[/code]

Then, I converted mysql functions in admin_menu.php

Initial code:

[code=php]
<?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;
?>
[/code]

Modified code:

[code=php]
<?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;
?>
[/code]

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!

to post a comment
PHP

17 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 07.2017 — 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:
[code=php]
<?php
error_reporting(E_ALL);
ini_set('display_errors', true); // set to false in production
[/code]

This should ensure you have some (hopefully) useful error messages to share with us wherever things break.
Copy linkTweet thisAlerts:
@visitor52authorNov 10.2017 — You can help us help you by actually testing it and letting us know what errors you get...[/QUOTE]

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
Copy linkTweet thisAlerts:
@NogDogNov 10.2017 — If you just want to die() when you don't connect like that, then the "or... needs to be part of the connection attempt:
[code=php]
<?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
[/code]
Copy linkTweet thisAlerts:
@visitor52authorNov 14.2017 — 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?
Copy linkTweet thisAlerts:
@visitor52authorNov 14.2017 — 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):
[code=php]<?
//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();

}
?>[/code]


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?
Copy linkTweet thisAlerts:
@visitor52authorNov 14.2017 — Moderator, please delete my last post as I accidentally posted info which I shouldn't post.
Copy linkTweet thisAlerts:
@NogDogNov 14.2017 — Moderator, please delete my last post as I accidentally posted info which I shouldn't post.[/QUOTE]

I just edited it to obfuscate the DB credentials.
Copy linkTweet thisAlerts:
@NogDogNov 14.2017 — 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):
[code=php]<?
//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();

}
?>[/code]


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?[/QUOTE]


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:
[code=php]
<?php
ini_set('display_errors', false);
error_reporting(E_ALL); // all warnings/errors will be in PHP error log
[/code]
Copy linkTweet thisAlerts:
@visitor52authorNov 14.2017 — 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:

[code=php]
<?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();
?>
[/code]


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?
Copy linkTweet thisAlerts:
@NogDogNov 14.2017 — 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...
[code=php]
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;
}
[/code]
Copy linkTweet thisAlerts:
@ginerjmNov 15.2017 — 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:

<i>
</i>ini_set('display_errors', true); // turn on errors while development
Copy linkTweet thisAlerts:
@NogDogNov 15.2017 — 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:

<i>
</i>ini_set('display_errors', true); // turn on errors while development
[/QUOTE]


Or just [B][FONT=Courier New]tail -f /path/to/php_errors.log[/FONT][/B] in a terminal window, if you know where the log file is. ¯_(&#12484?_/¯
Copy linkTweet thisAlerts:
@visitor52authorNov 19.2017 — Thank you, NodDog! I did what you suggested. It took me a few days to modify my old script and fix all errors shown in the PHP code checker, but now the script works just fine! And I didn't have to re-write it completely as one AH strongly suggested. All I had to do was really just to establish a MySQLi link to a database and then replace all MySQL functions with their MySQLi equivalents according to the PHP Manual. So, this was not an impossible task even for a noob like myself! But, of course, I couldn't do it without your help. Thank you so much for your constructive inputs! This is a great forum!
Copy linkTweet thisAlerts:
@benanamenNov 19.2017 — Welcome back forum coder, AKA Unique Idea Man, AKA UIman, and now AKA visiter52. You just keep going around to all the forums calling people an a-hole and you will be reported on every single one of them. You have already been banned from codingforums and earned a bad reputation under your many other usernames. Dont think coming here under yet another name is going to hide who you are.

You just keep posting on all the forums calling me an a-hole. Your bad reputation already precedes you which is why you are up to your what, 5th username now?

[B][COLOR="#FF0000"]CONSIDER YOURSELF REPORTED YET AGAIN[/COLOR][/B]
Copy linkTweet thisAlerts:
@rootNov 19.2017 — Well [B]Libel[/B] is writing something down that is also a false statement and that is damaging to your reputation... To start proceedings you need to visit a lawyer and have them start legal proceedings against that individual for damages and losses you have suffered as a direct result of being called an A hole.

If it is bothering you that much, then take the matter up with the site admins of that site, making a public post like you have is not the way to go about things, you are only lowering yourself to their level of mentality. Rise above it.
Copy linkTweet thisAlerts:
@ginerjmNov 19.2017 — I am fascinated by Benanamen's ability to research a person enough to identify them as a multiple personality poster. I'm retired but I don't have enough time to learn how to do that nor the desire to do it.

I wasn't sure who the OP was labeling but now I guess we all know. Glad it wasn't me!
Copy linkTweet thisAlerts:
@benanamenNov 19.2017 — It doesn't take any "research" at all. When the EXACT posts are made with several different usernames you would have to be an idiot to not know its the same person. When the OP admits it because he is called out by OTHER people, well, that speaks for itself. When a mod that has banned the OP posts that the multiple usernames are posting from the exact same IP, well, that also speaks for itself. But thanks for playing anyways.

When you read all the posts that OTHER users and mods have posted about this OP, you will understand why he is now on his 5th or so username.
×

Success!

Help @visitor52 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...