I'm trying to update database rows with api calls, but for some reason it comes up with this error:
Uncaught Error: Call to a member function fetch() on string
I'm not sure what it means by function on a string, since i apply it to an mysqli_stmt object.
This is how the put file looks like:
if (isset($authlvl)) {
if (ctype_space($authlvl) == false && $authlvl >= 3) {
if (isset($id) && ctype_space($id) == false) {
if (isset($id) && ctype_space($id) == false && $id !== null) {
$rule = $id;
$request = 'id';
} else if (isset($username) && ctype_space($username) == false && $username !== null) {
$rule = $username;
$request = 'username';
} else if (isset($email) && ctype_space($email) == false && $email !== null) {
$rule = $email;
$request = 'email';
} else if (isset($password) && ctype_space($password) == false && $password !== null) {
$rule = $password;
$request = 'password';
} else if (isset($image) && ctype_space($image) == false && $image !== null) {
$rule = $image;
$request = 'image';
} else {
$request = "1";
$rule = "2";
}
$post = new Post($db);
$result = $post->post($request, $rule);
$result->bind_result($previd, $prevusername, $prevemail, $prevpassword, $previmage, $prevauthlvl);
$result->store_result();
$num = $result->num_rows();
if ($num > 0) {
while ($result->fetch()) {
$put = new Put($db);
$result = $put->update(
isset($username) ? preg_replace('/\s+/', '', $username) : null,
isset($email) ? preg_replace('/\s+/', '', $email) : null,
isset($password) ? preg_replace('/\s+/', '', $password) : null,
isset($image) ? preg_replace('/\s+/', '', $image) : null,
isset($authlvl) ? preg_replace('/\s+/', '', $authlvl) : null,
$previd,
$prevusername,
$prevemail,
$prevpassword,
$previmage,
$prevauthlvl
);
echo $result;
}
} else {
echo "Couldn't update row. Reason: 404 Not Found";
}
} else {
echo "A valid id is required!";
}
} else {
echo "You are not authorized to peform this request!";
}
} else {
echo "You are not authorized to peform this request!";
}
The $username, $email ect... are calculated by a huge if statement mess, which i will not include right now, cause it has a lot of rows in use, but here is a small part of it:
$content = file_get_contents('php://input');
if (strpos($content, "email") !== false) {
$email = substr($content, (strpos($content, "email")) + 10, ((strpos($content, "-", strpos($content, "email"))) - strpos($content, "email")) - 12);
}
here is the post file, which does the post request:
class Post
{
private $conn;
public $id;
public $username;
public $email;
public $password;
public $image;
public $authlvl;
public function __construct($db)
{
$this->conn = $db;
}
public function post($request, $rule)
{
$format = "s";
if ($request == "id") {
$query = "SELECT * FROM users WHERE id=?";
$format = "i";
} else if ($request == "username") {
$query = "SELECT * FROM users WHERE username=?";
} else if ($request == "email") {
$query = "SELECT * FROM users WHERE email=?";
} else if ($request == "password") {
$query = "SELECT * FROM users WHERE password=?";
} else if ($request == "image") {
$query = "SELECT * FROM users WHERE image=?";
} else {
$query = "SELECT * FROM users";
}
if ($stmt = $this->conn->prepare($query)) {
$stmt->bind_param("" . $format . "", $rule);
$stmt->execute();
return $stmt;
} else {
echo "invalid string";
}
}
}
I'm testing the api with postman.
What i've already tried:
Storing the result inside the post file.
Redefining $stmt to the $stmt->execute() which gives me an false boolean error.
Converting the part in PDO (later found out you couldn't mix OOP with PDO)
Hard coded variables inside the put file, which also fails
If anyone has a solution, let me know :)
while ($result->fetch()) {
$put = new Put($db);
// Here you reassign $result which now is a string.
$result = $put->update(
isset($username) ? preg_replace('/\s+/', '', $username) : null,
isset($email) ? preg_replace('/\s+/', '', $email) : null,
isset($password) ? preg_replace('/\s+/', '', $password) : null,
isset($image) ? preg_replace('/\s+/', '', $image) : null,
isset($authlvl) ? preg_replace('/\s+/', '', $authlvl) : null,
$previd,
$prevusername,
$prevemail,
$prevpassword,
$previmage,
$prevauthlvl
);
echo $result;
}
You are reassigning $result in your loop.
So it executes once and then produces the above error message.
Related
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®='.$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();
Am using following lib to manage session, Am storing session values in database, everything works great i can get and set session values.
But after restart i can't get session values.
When i try to set session values i creates new row in database instead of updating.
LIB.php
<?php
/**
* #category Security
* #version 1.0
* #author First Last
* */
class mySessionHandler {
private $_db = NULL;
private $_table_name = 'sessions';
private $_cookie_name = 'session_cookie';
private $_seconds_till_expiration = 43200; // 2 hours
private $_renewal_time = 300; // 5 minutes
private $_expire_on_close = FALSE;
private $_ip_address = FALSE;
private $_user_agent = FALSE;
private $_secure_cookie = FALSE;
private $_session_id = FALSE;
private $_data = array();
public function __construct(array $config) {
$this->_setConfig($config);
if ($this->_read()) {
$this->_update();
} else {
$this->_create();
}
$this->_cleanExpired();
$this->_setCookie();
}
public function regenerateId() {
$old_session_id = $this->_session_id;
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ?, session_id = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id, $old_session_id));
$this->_setCookie();
}
public function setData($key, $value) {
$this->_data[$key] = $value;
$this->_write();
}
public function unsetData($key) {
if (isset($this->_data[$key])) {
unset($this->_data[$key]);
}
}
function getData($key) {
return isset($this->_data[$key]) ? $this->_data[$key] : FALSE;
}
public function getAllData() {
return $this->_data;
}
public function destroy() {
if (isset($this->_session_id)) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
setcookie($this->_cookie_name, '', time() - 31500000, NULL, NULL, NULL, NULL);
}
private function _read() {
$session_id = filter_input(INPUT_COOKIE, $this->_cookie_name) ? filter_input(INPUT_COOKIE, $this->_cookie_name) : FALSE;
if (!$session_id) {
return FALSE;
}
$this->_session_id = $session_id;
$stmt = $this->_db->prepare("SELECT data, time_updated, user_agent, ip_address FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if (!$this->_expire_on_close && (($result['time_updated'] + $this->_seconds_till_expiration) < time())) {
$this->destroy();
return FALSE;
}
if ($this->_ip_address && ($result['ip_address'] != $this->_ip_address)) {
$this->_flagForUpdate();
return FALSE;
}
if ($this->_user_agent && ($result['user_agent'] != $this->_user_agent)) {
$this->_flagForUpdate();
return FALSE;
}
$this->_checkUpdateFlag();
$this->_checkIdRenewal();
$user_data = unserialize($result['data']);
if ($user_data) {
$this->_data = $user_data;
unset($user_data);
}return TRUE;
}return FALSE;
}
private function _create() {
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("INSERT INTO {$this->_table_name} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)");
$stmt->execute(array($this->_session_id, $this->_user_agent, $this->_ip_address, time()));
}
private function _update() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id));
}
private function _write() {
if (count($this->_data) == 0) {
$custom_data = '';
} else {
$custom_data = serialize($this->_data);
}
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET data = ?, time_updated = ? WHERE session_id = ?");
$stmt->execute(array($custom_data, time(), $this->_session_id));
}
private function _setCookie() {
setcookie(
$this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + $this->_seconds_till_expiration, // Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}
private function _cleanExpired() {
if (mt_rand(1, 1000) == 1) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE (time_updated + {$this->_seconds_till_expiration}) < ?");
$stmt->execute(array(time()));
}
}
function _generateId() {
$salt = 'x7^!bo3p,.$$!$6[&Q.#,//#i"%[X';
$random_number = '9085723012206';
$random_txt = 'sanoj';
$ip_address_fragment = md5(substr(filter_input(INPUT_SERVER, 'REMOTE_ADDR'), 0, 5));
$hash_data = $random_number . $ip_address_fragment . $random_txt . $salt;
$hash = hash('sha256', $hash_data);
return $hash;
}
private function _checkIdRenewal() {
$stmt = $this->_db->prepare("SELECT time_updated FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ((time() - $this->_renewal_time) > $result['time_updated']) {
$this->regenerateId();
}
}
}
private function _flagForUpdate() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '1' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
private function _checkUpdateFlag() {
$stmt = $this->_db->prepare("SELECT flagged_for_update FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ($result['flagged_for_update']) {
$this->regenerateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '0' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
}
}
private function _setConfig(array $config) {
if (isset($config['database'])) {
$this->_db = $config['database'];
} else {
throw new Exception('Database handle not set!');
}
if (isset($config['cookie_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['cookie_name']))) {
throw new Exception('Invalid cookie name!');
} $this->_cookie_name = $config['cookie_name'];
}
if (isset($config['table_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['table_name']))) {
throw new Exception('Invalid table name!');
} $this->_table_name = $config['table_name'];
}
if (isset($config['seconds_till_expiration'])) {
if (!is_int($config['seconds_till_expiration']) || !preg_match('#[0-9]#', $config['seconds_till_expiration'])) {
throw new Exception('Seconds till expiration must be a valid number.');
}
if ($config['seconds_till_expiration'] < 1) {
throw new Exception('Seconds till expiration can not be zero or less. Enable session expiration when the browser closes instead.');
}
$this->_seconds_till_expiration = (int) $config['seconds_till_expiration'];
}
if (isset($config['expire_on_close'])) {
if (!is_bool($config['expire_on_close'])) {
throw new Exception('Expire on close must be either TRUE or FALSE.');
}
$this->_expire_on_close = $config['expire_on_close'];
}
if (isset($config['renewal_time'])) {
if (!is_int($config['renewal_time']) || !preg_match('#[0-9]#', $config['renewal_time'])) {
throw new Exception('Session renewal time must be a valid number.');
}
if ($config['renewal_time'] < 1) {
throw new Exception('Session renewal time can not be zero or less.');
}
$this->_renewal_time = (int) $config['renewal_time'];
}
if (isset($config['check_ip_address'])) {
if (!is_string($config['check_ip_address'])) {
throw new Exception('The IP address must be a string similar to this: \'172.16.254.1\'.');
}
if (!preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $config['check_ip_address'])) {
throw new Exception('Invalid IP address.');
}
$this->_ip_address = $config['check_ip_address'];
}
if (isset($config['check_user_agent'])) {
$this->_user_agent = substr($config['check_user_agent'], 0, 999);
} if (isset($config['secure_cookie'])) {
if (!is_bool($config['secure_cookie'])) {
throw new Exception('The secure cookie option must be either TRUE or FALSE.');
}
$this->_secure_cookie = $config['secure_cookie'];
}
}
}
How do i get session values even after restarting browser,
GET.PHP
ob_start();
session_start();
include_once('index.php');
echo $session->getData('fname').'<br>';
echo $session->getData('password').'<br>';
echo $session->getData('email').'<br>';
SET.PHP
ob_start();
session_start();
include_once('index.php');
$session->setData('fname', 'first last');
$session->setData('password', '123456');
$session->setData('email', 'first#last.com');
$sesi = $session->_generateId();
echo $sesi;
$_SESSION['test'] = $sesi;
try replacing _setCookie() so that your cookie won't expire
private function _setCookie() {
setcookie($this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + (10 * 365 * 24 * 60 * 60), //Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}
I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/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"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// 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 = "";
$reg_ok = true;
$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";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// 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 ((int)($res->counter) > 0) { // swear word founded!
// 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});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
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;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {
I've created a Logic Hook within the Leads module to save to a field in the database. The problem is that when I save the Lead first it displays a duplicate message:
Database failure error check SuiteCRM logs.
If I comment out this code the Lead is then saved.
LogicHook:
<?php
class LeadData
{
public function leadSaveData(&$bean, $events, $arguments)
{
$stateId = $bean->state_c;
if ($stateId != "") {
$beanst_state = BeanFactory::getBean('s1_state', $stateId);
$StateName = $beanst_state->name;
$bean->resstate_c = $StateName;
} else {
$bean->resstate_c = "Punjab";
}
if (!empty($bean->mediatype_c)) {
$mediaType = $bean->mediatype_c;
$callstatus = $bean->callstatus_c; //for follow up
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$bean->refrence_c = 'null';
} else if ($mediaType == 'Refrence') {
$bean->eventname_c = 'null';
} else {
$bean->mediatype_c = 'null';
$bean->refrence_c = 'null';
$bean->eventname_c = 'null';
}
if ($callstatus != 'followup') {
$bean->calllater_c = '0000-00-00 00:00:00';
}
$bean->save();
}
}
}
Please follow these steps in your code to make this error correct or working. Hope so it will helps you.
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
class saveextradata_logic_hooks_class
{
static $already_ran = false;
function saveextradata_after_save_method(&$bean, $events, $arguments)
{
global $db;
if (self::$already_ran == true) return;
self::$already_ran = true;
$lead_id = $bean->id;
$stateId = $_POST['state_c'];
$sql = "select name from s1_state where id='$stateId'";
$query = $db->query($sql);
$result = $db->fetchByAssoc($query);
$statename = $result[name];
if ($stateId != "") {
$statename;
} else {
$statename = "Punjab";
}
if (!empty($_POST['mediatype_c'])) {
$mediaType = $_POST['mediatype_c'];
if ($mediaType == 'Selectmedia' && $mediaType != '') {
$mediatype = 'Selectmedia';
$reference = 'null';
$eventname = $_POST['eventname_c'];
} else if ($mediaType == 'Refrence') {
$mediatype = 'Refrence';
$reference = $_POST['refrence_c'];
$eventname = 'null';
} else {
$mediatype = 'null';
$reference = 'null';
$eventname = 'null';
}
}
$callstatus = $_POST['callstatus_c'];//for follow up
if ($callstatus != 'followup') {
$calllater = '0000-00-00 00:00:00';
}
/*$bean->eventname_c = $eventname;
$bean->refrence_c = $reference;
$bean->mediatype_c = $mediatype_c;
$bean->calllater_c = $calllater;
$bean->resstate_c = $statename;
$bean->save();*/
$leadupdate = "update leads_cstm set resstate_c='$statename',eventname_c='$eventname',refrence_c='$reference',mediatype_c='$mediatype',calllater_c='$calllater' WHERE id_c = '$lead_id'";
$resultProductmasterdetail = $db->query($leadupdate);
}
}
I want to get the user by his email addresse or username ... but it doesn't work. Everytime i use a string and not a number, i just get false.
It's a school project so I can't use any frameworks :(
This doesn't work
$objAcc->getUser('email', 'example#gmail.com')
This works
$objAcc->getUser('user_id', '1')
Methode:
public function getUser($by = NULL, $value = NULL, $quantity = 0) {
global $database;
try {
$row = array();
if (isset($by) && isset($value)) {
$query = 'SELECT * FROM "user" WHERE :by=:value';
$stmt = $database->prepare($query);
$type = ($by == 'user_id' || $by == 'phone' || $by == 'fax' || $by == 'zip' || $by == 'admin') ? SQLITE3_INTEGER : SQLITE3_TEXT;
$stmt->bindValue(':by', $by, SQLITE3_TEXT);
$stmt->bindValue(':value', $value, $type);
$result = $stmt->execute();
} else {
$query = 'SELECT * FROM "user"';
$stmt = $database->prepare($query);
$result = $stmt->execute();
}
if ($quantity) {
for ($i = 0; $i < $quantity; $i++) {
$row[ $i ] = $result->fetchArray(SQLITE3_ASSOC);
}
} else {
$i = 0;
while ($entry = $result->fetchArray(SQLITE3_ASSOC)) {
$row[ $i ] = $entry;
$i++;
}
}
if (empty($row[0])) {
return FALSE;
}
return $row;
} catch (Exception $e) {
var_dump($e);
die();
}
}
I hope you can help me guys.
I don't think you can use binding for column names. I would suggest to create the SQL statement dynamically, but only after you have validated that the $by argument matches with an existing column name (avoid risk of SQL injection):
$numFields = array("user_id", "phone", "fax", "zip", "admin");
$charFields = array("email");
$allFields = array_merge($numFields, $charFields);
$row = array();
if (isset($by) && isset($value) && in_array($by, $allFields)) {
$query = 'SELECT * FROM "user" WHERE ' . $by . '=:value';
$stmt = $database->prepare($query);
$type = in_array($numFields, $by) ? SQLITE3_INTEGER : SQLITE3_TEXT;
$stmt->bindValue(':value', $value, $type);
} else {
$query = 'SELECT * FROM "user"';
$stmt = $database->prepare($query);
}
$result = $stmt->execute();