Problems with mysql and mysqli - php

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in C:\xampp\htdocs\swift\core\functions\general.php on line 49
Notice: Undefined variable: conn in
C:\xampp\htdocs\swift\core\functions\users.php on line 85
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\swift\core\functions\users.php on line 85
Fatal error: Uncaught Error: Call to undefined function
mysqli_result() in C:\xampp\htdocs\swift\core\functions\users.php:86
Stack trace: #0 C:\xampp\htdocs\swift\loginact.php(14): f_exists('')
#1 {main} thrown in C:\xampp\htdocs\swift\core\functions\users.php on line 86
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
This is the General.php.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function activation($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function recovery_user_pass($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function f_protect_page() {
if(f_logged_in() === false) {
header('Location: flogin.php');
exit();
}
}
function user_protect_page() {
if(f_logged_in() === false) {
header('Location: fprotect.php');
exit();
}
}
function use_protect_page() {
if(f_logged_in() === true) {
header('Location: fprotect.php');
exit();
}
}
function f_logged_in_redirect() {
if(f_logged_in() === true) {
header('Location: index.php');
exit();
}
}
function array_sanitize($item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($item)));
}
function sanitize($data) {
return htmlentities(strip_tags(mysqli_real_escape_string($data)));
}
function output_errors($errors) {
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
?>
this is the USERS.PHP can someone please check this.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function f_recover($mode, $f_mailid) {
$mode = sanitize($mode);
$f_mailid = sanitize($f_mailid);
$f_data = f_data(f_id_from_email($f_mailid),'f_id','f_fname','f_uname');
if ($mode == 'f_uname') {
recovery_user_pass($f_mailid, 'Recovery: Your username', "Hello " . $f_data['f_fname'] . ",\n\nYour username is: " . $f_data['f_uname'] . "\n\n-Swift Airlines");
}
else if($mode == 'f_password') {
$generated_password = substr(md5(rand(999, 999999)), 0, 8);
f_change_password($f_data['f_id'], $generated_password);
update_f($f_data['f_id'], array('f_passrec' => '1'));
recovery_user_pass($f_mailid, 'Recovery: Your password', "Hello " . $f_data['f_fname'] . ",\n\nYour new password is: " . $generated_password . "\n\n-TOFSIS");
}
}
function f_activate($f_mailid, $f_mailcode) {
$f_mailid = mysqli_real_escape_string($_POST['f_mailid']);
$f_mailcode = mysqli_real_escape_string($_POST['f_mailcode']);
if(mysqli_result(mysqli_query("SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid` = '$f_mailid' AND `f_mailcode` = '$f_mailcode' AND `f_active` = 0"), 0) == 1) {
mysqli_query("UPDATE `flight_users` SET `f_active` = 1 WHERE `f_mailid` = '$f_mailid' ");
return true;
}
else {
return false;
}
}
function update_f($f_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field => $data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysqli_query("UPDATE `flight_users` SET " . implode(', ',$update) . "WHERE `f_id` = $f_id") or die(mysqli_error($conn));
}
function f_change_password($f_id, $f_password) {
$f_id = (int)$f_id;
$f_password = md5($f_password);
mysqli_query("UPDATE `flight_users` SET `f_password` = '$f_password', `f_passrec` = 0 WHERE `f_id` = $f_id");
}
function register_f($register_data) {
array_walk($register_data, 'array_sanitize');
$register_data['f_fname'] = ucwords(strtolower($register_data['f_fname']));
$register_data['f_lname'] = ucwords(strtolower($register_data['f_lname']));
$register_data['f_password'] = md5($register_data['f_password']);
$register_data['f_uname'] = strtolower($register_data['f_uname']);
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysqli_query("INSERT INTO `flight_users` ($fields, `f_regdate`) VALUES ($data, NOW())");
activation($register_data['f_mailid'], 'Swift Airlines: Activate your account', "Hello " . $register_data['f_fname'] . ", \n\nYou need to activate your account in order to use the features of Swift Airlines. Please click the link below: \n\nhttp://srikanthnatarajan.com/swift/activate.php?f_mailid=" . $register_data['f_mailid'] . "&f_mailcode=" . $register_data['f_mailcode'] . " \n\n-Swift Airlines");
}
function f_data($f_id){
$data = array();
$f_id = (int)$f_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args) . '`';
$data = mysqli_fetch_assoc(mysqli_query("SELECT $fields FROM `flight_users` WHERE `f_id` = $f_id"));
return $data;
}
}
function f_logged_in() {
return (isset($_SESSION['f_id'])) ? true : false;
}
function f_exists($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_email_exists($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid`= '$f_mailid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_regid_exists($f_regid) {
$f_regid = sanitize($f_regid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_regid`= '$f_regid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_active($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_active` = 1");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_id_from_username($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_uname` = '$f_uname'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_id_from_email($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_mailid` = '$f_mailid'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_login($f_uname, $f_password) {
$f_id = f_id_from_username($f_uname);
$f_uname = sanitize($f_uname);
$f_password = md5($f_password);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_password` = '$f_password'");
return (mysqli_result($conn, $query, 0) == 1) ? $f_id : false;
}
?>
and this is the Loginact.php------------------
<?php
$title = 'Swift Airlines | Login Error';
include $_SERVER["DOCUMENT_ROOT"].'/swift/core/init.php';
if(empty($_POST) === false) {
$f_uname = $_POST['f_uname'];
$f_password = $_POST['f_password'];
if(empty($f_uname) === true || empty($f_password) === true){
$errors[] = 'You need to enter both, the username and the password!';
}
else if (f_exists($f_uname)===false) {
$errors[] = 'No such user exists! Please register!';
}
else if(f_active($f_uname)===false) {
$errors[] = 'Please activate your account!';
}
else {
if(strlen($f_password)>32) {
$errors[] = 'Password too long!';
}
$f_login = f_login($f_uname, $f_password);
if($f_login===false) {
$errors[] = 'Username and Password do not match!';
}
else {
$_SESSION['f_id'] = $f_login;
header('Location: http://localhost/swift/index.php');
exit();
}
}
}
else {
$errors[] = 'No Log In credentials received!';
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/header.php';
if(empty($errors) === false) {
?>
<br/><h4>We tried to log you in, but : </h4><br/>
<?php
echo output_errors($errors);
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/footer.php';
?>
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
i know php is kind of hard yea and ive been looking for the answer for almost a day now. Im just new to programming and im doing my best to study hard about these kind of things hopefully someone can help me.
And i hope i can learn more about php and other programming language here.. ill keep looking for the answer even if im asking right now.. big thanks though.

I doubt you tried everything!
It looks as if you are trying to migrate from mysql_ functions to mysqli_.
From the manual for mysqli_fetch_array:
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
$link is your mysqli connection. In your code it is $conn.
Within your functions you have a scope issue. $conn is in the global scope, so is not set within the function's scope.
Break it down, start with something like your f_id_from_email function, and follow and try to translate the manual's examples.
The error messages are actually quite helpful if read. But you are likely overwhelmed, as you are faced with many.
Call to undefined function mysqli_result()
That's because there is no mysqli_result function.

1- general.php line 49: look at mysqli_real_escape_string, in procedural code, you must specify 2 arguments, the link (or connection) and the string.
function array_sanitize($conn,$item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($conn,$item)));
}
function sanitize($conn,$data) {
return htmlentities(strip_tags(mysqli_real_escape_string($conn,$data)));
}
2- users.php, both on line 85, the $conn does not exist in the scope of the function. Pass $conn as an argument to the function and call it with ($conn,$f_uname).
function f_exists($conn,$f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
3- your question at line 86, it is the same as my #2 point.

Related

Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4

I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'";
// for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true&reg='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();

Undefined Variable: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given

I'm moving an older PHP script over to mysqli queries, I'm having trouble with mysqli_real_escape_string in validation code for signups.
PHP message: PHP Notice: Undefined variable: link in
/srv/www/public_html/classes/validation.class.php on line 38
PHP message: PHP Warning: mysqli_real_escape_string() expects
parameter 1 to be mysqli, null given in
/srv/www/public_html/classes/validation.class.php on line 38" while
reading response header from upstream
validation.class.php as follows;
<?php
defined('_VALID') or die('Restricted Access!');
class VValidation
{
public function username($username)
{
if (!preg_match('/^[a-zA-Z0-9_]*$/', $username)) {
return false;
} elseif (preg_match('/^[_]*$/', $username)) {
return false;
}
$users_blocked = array(
'edit',
'prefs',
'blocks',
'delete',
'avatar'
);
if (in_array($username, $users_blocked)) {
return false;
}
return true;
}
public function usernameExists($username) {
global $conn;
$sql = "SELECT UID FROM signup WHERE username = '" . mysqli_real_escape_string($username) . "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function email($email)
{
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
public function emailExists($email, $uid = NULL) {
global $conn;
$sql_add = (isset($uid)) ? " AND UID != " . intval($uid) : NULL;
$sql = "SELECT UID FROM signup WHERE email = '" . mysql_real_escape_string($email) . "'" . $sql_add . " LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function date($month, $day, $year) {
return checkdate($month, $day, $year);
}
public function age($month, $day, $year, $years)
{
$age = mktime(0, 0, 0, $month, $day, $year);
$real_age = mktime(0, 0, 0, date('m'), date('d'), (date('Y') - $years));
if ($age <= $real_age) {
return true;
}
return false;
}
public function zip($code, $country = 'US') {
if (!ctype_digit($code)) {
return false;
}
$length = VString::strlen($code);
switch ($country) {
case 'UK':
case 'CA':
if ($length <> 6) {
return true;
}
default:
if ($length >= 5 && $lenght <= 9) {
return true;
}
}
return false;
}
public function ip($ip)
{
if (!ip2long($ip)) {
return false;
}
}
}
?>
I've wrongly(?) assumed I can include my config to get database details;
<?php
defined('_VALID') or die('Restricted Access!');
require_once $config['BASE_DIR']. '/include/config.php';
and $link mysqli_real_escape_string
$sql = "SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
But this provides the above errors. The include to config.php contains includes to other configs to bring it all together.
<?php
defined('_VALID') or die('Restricted Access!');
require 'config.db.php';
require $config['BASE_DIR']. '/include/dbconn.php';
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$config['db_pass'], $config['db_name']);
if ( !defined('_CONSOLE') ) {
require $config['BASE_DIR']. '/include/sessions.php';
}
disableRegisterGlobals();
... more unreleated functions
config.db.php
<?php
defined('_VALID') or die('Restricted Access!');
$config['db_type'] = 'mysqli';
$config['db_host'] = 'localhost';
$config['db_user'] = 'user1';
$config['db_pass'] = 'abc123';
$config['db_name'] = 'newdatabase';
?>
db.conn.php
<?php
defined('_VALID') or die('Restricted Access!');
$conn = ADONewConnection($config['db_type']);
if ( !$conn->Connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']) ) {
echo 'Could not connect to mysql! Please check your database settings!';
die();
}
$conn->execute("SET NAMES 'utf8'");
?>
Am I going about this the right way? Thanks for any info.
public function usernameExists($username )
{
global $conn, $config;
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$sql="SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}

Generic PHP function to get data from MySQL database

I'm creating a web application that relies heavily upon getting data from MySQL using PHP. In ~50 functions I have very similar code requesting single data values from MySQL:
function get_profile_picture($whatmember) {
global $connection;
$whatmember = mysql_prep($whatmember);
$query = "SELECT picture_location FROM members WHERE member_id={$whatmember} LIMIT 1";
$returnval = mysqli_query($connection,$query);
if(!$returnval) {
return "Query failed: " . mysqli_error($connection);
}
if(mysqli_num_rows($returnval) > 0 ) {
$row = mysqli_fetch_assoc($returnval);
return $row["picture_location"];
}
return false;
}
So my question is this: is there a generic AND safe way to make the function so that I can just input "SELECT what-value FROM what-database.what-table WHERE what-criteria=what-value" that allows for arrays of results as well as single values? I made an attempt with the following, but it obviously is a hack and slash method that only gets single values:
function get_single_value($database_name,$column_name,$table_name,$criteria,$criteria_value) {
$database_name = mysql_prep($database_name);
$column_name = mysql_prep($column_name);
$table_name = mysql_prep($table_name);
$criteria = mysql_prep($criteria);
$criteria_value = mysql_prep($criteria_value);
if(!empty($column_name) && !empty($table_name) && !empty($criteria) && !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else {
die("Database connection doesn't exist for {$database_name}.");
}
$query = "SELECT {$column_name} FROM {$table_name} WHERE {$criteria}='{$criteria_value}' LIMIT 1";
$result = mysqli_query($database_connection,$query);
if(!$result) {
die("Unable to get {$column_name} from {$table_name}. Error: " . mysqli_error($database_connection) . " Query: " . $query);
}
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
return $row[$column_name];
}
}
return false;
}
And my get_profile_picture() function would then look more like this:
function get_profile_picture($whatmember) {
return get_single_value("connection","picture_location","members","member_id",$whatmember);
}
I'm still pretty new to PHP and MySQL so any pointers to improve my code would be great as well. Thanks in advance!
Alright I wrote my own. It might not have all the security of PDO, but I don't have the learn another framework in order to use it.
function get_from_database($database_variable) {
//PASS IN $database_variable WHICH IS AN OBJECT CONTAINING THE FOLLOWING POSSIBLE VALUES
$database_name = $database_variable["database_name"]; //DATABASE NAME
$column_name = $database_variable["column_name"]; //COLUMN(S) BEING REQUESTED
$table_name = $database_variable["table_name"]; //TABLE BEING SEARCHED
$criteria = $database_variable["criteria"]; // 'WHERE X'
$limit = $database_variable["limit"]; //ANY LIMITS, IF REQUIRED
$group_by = $database_variable["group_by"]; //ANY GROUPING, IF REQUIRED
$order_by = $database_variable["order_by"]; //ANY SORT ORDERING, IF REQUIRED
if(!empty($column_name) && !empty($table_name)&& !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
global $olddataconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else if ($database_name=="olddata") {
$database_connection = $olddataconnection;
} else {
error_log("\nDatabase connection doesn't exist for {$database_name}." . get_backtrace_info());
return false;
}
if(is_null($limit)) {
//IF LIMIT NOT SUPPLIED, MAKE LIMIT 0, IE NO LIMIT
$limit = 0;
}
if(is_int($limit)==false) {
//NOT AN INTEGER
error_log("\nError in limit provided: " . $limit . get_backtrace_info());
return false;
}
$query = " SELECT {$column_name}
FROM {$table_name} " . (!empty($criteria) /*CHECK IF CRITERIA WAS REQUIRED*/ ? "
WHERE {$criteria} " : "") . (!empty($group_by) /*CHECK IF GROUP BY WAS REQUIRED*/ ? "
GROUP BY {$group_by} " : "") . (!empty($order_by) /*CHECK IF ORDER BY WAS REQUIRED*/ ? "
ORDER BY {$order_by} " : "") . ($limit!==0 /*CHECK IF LIMIT WAS REQUIRED*/ ? "
LIMIT {$limit} " : "");
$result = mysqli_query($database_connection,$query);
if(!$result) {
error_log("\nUnable to process query, got error: " . mysqli_error($database_connection) . "\nQuery: " . $query . get_backtrace_info());
return false;
}
if(mysqli_num_rows($result)>0) {
//RESULT SUPPLIED
$row_array = array();
while($row = mysqli_fetch_assoc($result)) {
$row_array[] = $row;
}
mysqli_free_result($result);
return $row_array;
}
}
return false;
}
Function to trace function call back to source:
function get_backtrace_info(){
//GET INFORMATION ON WHICH FUNCTION CAUSED ERROR
$backtrace = debug_backtrace();
$backtrace_string = "";
for($i=0;$i<count($backtrace);$i++) {
$backtrace_string .= '\n';
if($i==0) {
$backtrace_string .= 'Called by ';
} else {
$backtrace_string .= 'Which was called by ';
}
$backtrace_string .= "{$backtrace[$i]['function']} on line {$backtrace[$i]['line']}";
}
return backtrace_string;
}
Now I can request data from MySQL as follows:
Single value requested:
function get_profile_picture($whatmember) {
$linked_member_code = get_linked_member_code($whatmember);
return get_from_database([ "database_name" => "connection",
"column_name" => "picture_location",
"table_name" => "members",
"criteria" => "linked_member_code='{$linked_member_code}' AND team_id=0",
"limit" => 1
])[0]["picture_location"];
}
2 values requested:
function get_city_and_region_by_id($whatid) {
$row = get_from_database([ "database_name" => "locations",
"column_name" => "city, region",
"table_name" => "cities",
"criteria" => "row_id={$whatid}",
"limit" => 1
]);
return $row[0]["city"] . ", " . $row[0]["region"];
}
Unknown number of rows:
function get_linked_teams($linkedmembercode) {
return get_from_database([ "database_name" => "connection",
"column_name" => "team_id",
"table_name" => "members",
"criteria" => "linked_member_code='{$linkedmembercode}' AND team_id!=0"
]);
}

PHP Class not Returning Result

I am working on an Item Inventory Web App. I want users should be able to add and assign item to a user. Each user is entitled to one item at a time. If, say, user a already has an item assigned and you want to add more item, the system should lodge an error that will tell you
to withdraw the item be issuing a new one but the errors are not getting lodged in the error[] array even though it shows that the array is not empty. It only echo out the serial number a = 1 and a++ but the text is not there.
class.inc.php
class Summary {
public $result;
public $conn;
public $SQ;
public $q;
public $updateDB;
public $checkDB;
public $returned_result;
public $a;
public $data;
public $col;
public function __construct(){
$this->conn = new PDO('mysql:host=localhost; dbname=dB', 'root', '');
$this->conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function updateDB($coloumn, $data, $id){
$SQ = "UPDATE mytable SET $coloumn = ? WHERE staffID = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $id);
if ($q->execute()){
$success = 'Record updated successfully';
};
return $success;
}
public function checkDB($col, $data){
$status = 'Active';
$SQ = "SELECT surname FROM mytable WHERE $col = ? AND status = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $status);
$q->execute();
if($result = $q->fetch(PDO::FETCH_BOTH)){
$a = $result[0];
if ($a == ''){
$this->returned_result = 'N';
}
else {
$this->returned_result = "This item (". $data . ") is in use by ". $a . ". Please widthraw the item";
}
}
return $this->returned_result;
}
}
index.php:
include('class.inc.php');
$summary = new Summary;
$error = array();
if(isset($_POST['saveRecord']) ) {
$system_name = strtoupper ( $_POST['system_name'] );
$result =$summary->checkDB('systemName', $system_name); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('systemName', $system_name, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
$system_serial_number = strtoupper ( $_POST['system_serial_number'] );
$result =$summary->checkDB('CPUSerial', $system_serial_number); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('CPUSerial', $system_serial_number, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
}
if(isset($_POST['saveRecord']) && !empty( $error ) ) {
echo "<div class = 'text-error'>";
$a = 1;
foreach ($error as $err){
echo '<p>' . $a . '. ' .$err . '</p>';
$a++;
}
echo "</div>";
}
Any help will be greatly appreciated. And what am I doing wrong with regards to OOP way of programming?

mysql_fetch_array(): supplied argument is not a valid MySQL

Warning:mysql_fetch_array(): supplied argument is not a valid MySQL result resource in **/home/davzyco1/public_html/notes/functions.php** on line 43
was the error I got when I use the below class, even though the class works PERFECTLY with my old webhost. Here's my new hosts php info: http://davzy.com/notes/php.php
class mysqlDb
{
public $con;
public $debug;
function __construct($host,$username,$password,$database)
{
$this->con = mysql_connect($host,$username,$password);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $this->con);
}
function kill()
{
mysql_close($this->con);
}
function debugOn()
{
$this->debug = true;
}
function debugOff()
{
$this->debug = false;
}
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
function update($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br><br>";
}
}
function updateModern($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET `{$id}` = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br>";
}
}
function delete($t, $w)
{
mysql_query("DELETE FROM `{$t}` WHERE {$w}");
if($this->debug == true)
echo "DELETE FROM `{$t}` WHERE {$w}<br><br>";
}
function insert($where, $array)
{
$sql = "INSERT INTO `{$where}` (";
$sql2 = " VALUES (";
foreach($array as $id => $value){
$sql .= "`{$id}`, ";
$sql2 .= "'{$value}', ";
}
mysql_query(str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");"));
if($this->debug == true)
echo str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");")."<br><br>";
}
}
This is because mysql_query() will return FALSE if an error occured, instead of returning a result resource. You can check the error by calling mysql_error(), as shown here:
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
if (!$result) {
// an error occured, let's see what it was
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
Based on the error message, you can find out what the real problem is.
You should really test to see if $result is not false before using it with mysql_fetch_array. The error you're receiving is indicative that the query itself failed.
Have you configured your database with your new host? (do all the tables exist?)
As Mark said above, you really should check your result before trying mysql_fetch_array on a result set, and verify that all tables actually exist.
Without knowing how your original server was set up, I can only guess, but it may also be that your old server was set up to not display warnings.

Categories