Why doesn't this work? sqlit3 php - php

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();

Related

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

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() {

Cannot Use a Scalar Value as an Array, But Data Successfully Updated

I have this code :
public function updateSegmentGender ($product_id, $segment_gender) {
$this->connect();
$product_id = $this->escapeString($product_id);
$row_count = count($segment_gender);
for ($row = 0; $row < $row_count; $row++) {
$this->select('product_seg_gender', '*', NULL,
'product_id = "'.$product_id.'" AND gender = "'.$segment_gender[$row][0].'"', NULL, NULL);
$res = $this->getResult();
$res = count($res);
$gender = $segment_gender[$row][0];
$status = $segment_gender[$row][1];
if ($res <> 0) {
// UPDATE
$data = array ('status'=>$status);
$this->update('product_seg_gender', $data, 'product_id = "'.$product_id.'" AND gender = "'.$gender.'"');
}else {
// INSERT
$data = array ('product_id'=>$product_id, 'gender'=>$gender, 'status'=>$status);
$this->insert('product_seg_gender', $data);
}
}
}
and I'm using that method like this :
$user = new Product($db_server, $db_user, $db_password, $db_name);
$user->connect();
$segment_gender = array ( array ("all", "active"),
array ("female", "active"));
$res = $user->updateSegmentGender ('303', $segment_gender);
print_r($res);
but why I always got this error message :
Warning: Cannot use a scalar value as an array in /home/***/public_html/class/Database.class.php on line 130
however, the database is successfully updated. what did I do wrong?
UPDATE : here's complete line 97-145 of Database.class.php
// Function to SELECT from the database
public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){
// Create query from the variables passed to the function
$q = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$q .= ' JOIN '.$join;
}
if($where != null){
$q .= ' WHERE '.$where;
}
if($order != null){
$q .= ' ORDER BY '.$order;
}
if($limit != null){
$q .= ' LIMIT '.$limit;
}
// echo $table;
$this->myQuery = $q; // Pass back the SQL
// Check to see if the table exists
if($this->tableExists($table)){
// The table exists, run the query
$query = $this->myconn->query($q);
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = $query->num_rows;
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = $query->fetch_array();
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if($query->num_rows >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result[$i][$key[$x]] = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,$this->myconn->error);
return false; // No rows where returned
}
}else{
return false; // Table does not exist
}
}
Note: I hope you require $res = $user->updateSegmentGender ('303', $segment_gender); need $data value and based on assumption I use $data for return part.
Perhaps due to $data not initialized. I'm trying to declaring the variable $data, as an array, before using it I also make another change that function updateSegmentGender() require return part so I put this.
public function updateSegmentGender ($product_id, $segment_gender) {
$this->connect();
$product_id = $this->escapeString($product_id);
$row_count = count($segment_gender);
$data = array();//Initialize variable...
for ($row = 0; $row < $row_count; $row++) {
$this->select('product_seg_gender', '*', NULL,
'product_id = "'.$product_id.'" AND gender = "'.$segment_gender[$row][0].'"', NULL, NULL);
$res = $this->getResult();
$res = count($res);
$gender = $segment_gender[$row][0];
$status = $segment_gender[$row][1];
if ($res <> 0) {
// UPDATE
$data = array ('status'=>$status);
$this->update('product_seg_gender', $data, 'product_id = "'.$product_id.'" AND gender = "'.$gender.'"');
}else {
// INSERT
$data = array ('product_id'=>$product_id, 'gender'=>$gender, 'status'=>$status);
$this->insert('product_seg_gender', $data);
}
}
//Return funal value in array format...
return $data;
}

getting information from database with php

I'm making API to simple forum ,,
Now trying to get the information from the Database and show it
on the control page :
showForums.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TheForums</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('fourmsAPI.php');
/*
function tinyf_forums_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `forums` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$forums = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($forums)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $forums;
}
*/
$forums = tinyf_forums_get();
if($forums == NULL)
{
die('problem');
}
$fcount = count($forums);
if($fcount == 0)
{
die('No Forums ');
}
?>
<ul type = "square">
<?php
for($i = 0 ; $i < $ucount ; $i++)
{
$forum = $forums[$i];
echo "<li><a href = \"forums.php?id=$forum->id\"> $forum->title <a/> <br/> $forum->desc <br/> </li>"; //$array ->
}
?>
</ul>
</body>
</html>
The Result ===> 'problem'
The Apifile:
fourmsAPI.php
<?php
//Forums APIs
function tinyf_forums_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `forums` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$forums = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($forums)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $forums;
}
function tinyf_forums_get_by_id($fid)
{
$id = (int)$fid;
if($fid == 0 )
return NULL ;
$result = tinyf_forums_get('WHERE id ='.$id);
if($result == NULL)
return NULL;
$forum = $result[0];
return $forum;
}
//get result is array()
function tinyf_forums_get_by_name($name)
{
global $tf_handle;
$n_name = mysqli_real_escape_string($tf_handle, strip_tags($name));
$result = tinyf_users_get("WHERE `name` = '$n_name'");
if ($result != NULL){
$user = $result[0];
}
else{
$user = NULL;
}
return $user ;
}
function tinyf_forums_get_by_email($email)
{
global $tf_handle;
$n_email = mysqli_real_escape_string($tf_handle, strip_tags($email));
$result = tinyf_users_get("WHERE `email` = '$n_email' ");
if ($result != NULL)
{
$user = $result[0];
}
else{
$user = NULL ;
}
return $user ;
}
function tinyf_forums_add($title,$desc)
{
global $tf_handle;
if ((empty($title)) || (empty($desc)))
return false;
$n_title = mysqli_real_escape_string($tf_handle, strip_tags($title));
$n_desc = mysqli_real_escape_string($tf_handle, strip_tags($desc));
$query = sprintf("INSERT INTO `forums` VALUE(NULL,'%s','%s')",$n_title,$n_desc);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_forums_delete($fid)
{
global $tf_handle;
$id = (int)$fid;
if($id == 0 )
return false ;
tinyf_forums_delete_all_posts($fid);
$query = sprintf ("DELETE FROM `forums` WHERE `id`= %d",$id);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_forums_update($fid,$title = NULL,$desc = NULL)
{
global $tf_handle;
$id = (int)$uid;
if($id == 0 )
return false ;
$forum = tinyf_forums_get_by_id($id);
if(!$forum)
return false;
if ((empty($title)) && (empty($desc)))
return false;
$fields = array() ;
$query = 'UPDATE `forums` SET ' ;
if(!empty($title))
{
$n_title = mysqli_real_escape_string($tf_handle, strip_tags($title));
$fields[count($fields)] = "`title` = '$n_title'";
}
if(!empty($desc))
{
$n_name = mysqli_real_escape_string($tf_handle,strip_tags($name));
$fields[count($fields)] = "`desc` = '$n_desc'";
}
for($i = 0; $i < $fcount ; $i++)
{
$query .= $fields[$i];
if($i != ($fcount - 1)) // i = 0 that the first element in the array .. 2 will be - 1 last 3shan hwa by3ed el array mn wa7ed :D
$query .=' , ';
}
$query .= ' WHERE `id` = '.$id;
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
else
return true;
}
function tinyf_forums_delete_all_posts($fid)
{
global $tf_handle;
$id = (int)$fid;
if($id == 0){
return false;
}
$forums = tinyf_forums_get_by_id($id);
if(!$forum){
return false;
}
$topicsq = sprintf('SELECT * FROM `posts` WHERE `fid` = %d',$id) ;
$tresult = mysqli_query($tf_handle,$topicsq);
if(!$tresult){
return false;
}
$tcount = mysqli_num_rows($result);
for($i = 0; $i<$tcount ; $i++){
$topic = mysqli_fetch_object($tresult);
mysqli_query($tf_handle,'DELETE FROM `posts` WHERE `pid` = '.$topic ->id);
mysqli_query($tf_handle,'DELETE FROM `posts` WHERE `id` = '.$topic ->id);
}
mysqli_free_result($tresult);
return true ;
}
include ('db.php') ;
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
i expected it will show the information
i think the function tinyf_forums_get() is causing that
Your code is broken:
You define an array, then never use it:
$forums = array();
$users[count($forums)] = mysqli_fetch_object($qresult);
^^^^^---undefined, never returned, never used otherwise, therefore useless.
return $forums;
^^^^^^---returning permanently empty array
and since $forums is an empty array:
php > $x = array();
php > var_dump($x == null);
bool(true)
You probably want
if (count($forums) == 0)
instead.

Cannot redeclare my function php

I use Linux Debian
Local Lamp Server
i tried to make connection between Database and php & making API :
db.php (the connection file !) :
<?php
$tf_host = 'localhost' ;
$tf_dbname = 'tinyforum' ;
$tf_username = 'root';
$tf_password = '976431' ;
$tf_handle = mysqli_connect($tf_host , $tf_username , $tf_password,$tf_dbname);
if (!$tf_handle){
die('connection problem ..');
}
$tf_db_result = mysqli_select_db($tf_handle,$tf_dbname);
mysqli_query($tf_handle, "SET NAMES 'utf8'") ;
function tinyf_db_close() {
global $tf_handle;
mysqli_close($tf_handle);
}
?>
i tried to run this file ===>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!isset($_POST['username']) or (!isset($_POST['password'])) or (!isset($_POST['email']))) {
die('bye');
}
require_once('db.php');
require_once ('usersAPI.php');
$result = tinyf_users_add($_POST['username'],$_POST['password'],$_POST['email'], 0);
tinyf_db_close();
if($result) {
die('yes');
}
else {
die('no');
}
i get error:
Fatal error: Cannot redeclare tinyf_db_close() (previously declared in /var/www/html/tinyforum/db.php:21) in /var/www/html/tinyforum/db.php on line 21
code of usersAPI.php
<?php
//Users APIs
function tinyf_users_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `users` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$users = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($users)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $users;
}
function tinyf_users_get_by_id($uid)
{
$id = (int)$uid;
if($id == 0 )
return NULL ;
$result = tinyf_users_get('WHERE id ='.$id);
if($result == NULL)
return NULL;
$user = $result[0];
return $user;
}
function tinyf_users_add($name,$password,$email,$isadmin)
{
global $tf_handle;
if ((empty($name)) || (empty($password)) || (empty($email)))
return false;
$n_email = mysqli_real_escape_string($tf_handle, strip_tags($email));
if(!filter_var($n_email,FILTER_VALIDATE_EMAIL))
return false;
$n_name = mysqli_real_escape_string($tf_handle, strip_tags($name));
$n_pass = md5(mysqli_real_escape_string($tf_handle, strip_tags($password)));
$n_isadmin = (int)$isadmin;
if(($n_isadmin != 0) && ($n_isadmin != 1))
$n_isadmin = 0 ;
$query = sprintf("INSERT INTO `users` VALUE(NULL,'%s','%s','%s','%d')",$n_name,$n_pass,$n_email,$n_isadmin);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_users_delete($uid)
{
global $tf_handle;
$id = (int)$uid;
if($id == 0 )
return false ;
$query = sprintf ("DELETE FROM `users` WHERE `id`= %d",$id);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_users_update($uid,$name = NULL,$password = NULL ,$email = NULL,$isadmin = -1)
{
global $tf_handle;
$id = (int)$uid;
if($id == 0 )
return false ;
$n_isadmin = (int)$isadmin ; // if 0 = FALSE not int ,,, if int = 1
$user = tinyf_users_get_by_id($id);
if(!$user)
return false;
if ((empty($name)) && (empty($password)) && (empty($email)) && ($user -> isadmin == $n_isadmin))
return false;
$fields = array() ;
$query = 'UPDATE `users` SET ' ;
if(!empty($email))
{
$n_email = mysqli_real_escape_string($tf_handle, strip_tags($email));
if(!filter_var($n_email,FILTER_VALIDATE_EMAIL))
return false;
$fields[count($fields)] = "`email` = '$n_email'";
}
if(!empty($name))
{
$n_name = mysqli_real_escape_string($tf_handle,strip_tags($name));
$fields[count($fields)] = "`name` = '$n_name'";
}
if(!empty($password))
{
$n_pass = md5(mysqli_real_escape_string($tf_handle, strip_tags($password)));
$fields[count($fields)] = "`password` = '$n_pass'";
}
if($n_isadmin == -1)
{
$n_isadmin = $user -> isadmin ;
}
elseif ($n_isadmin > 1)
{
$n_isadmin = $user -> isadmin ;
}
$fields[count($fields)] = "`isadmin` = $n_isadmin";
$fcount = count($fields);
if($fcount == 1)
{
$query .= $fields[0].'WHERE `id`= ' .$id ; // $query = 'UPDATE `users` SET '
$qresult = mysqli_query($tf_handle, $query);
if(!qresult)
return false;
else
return true;
}
for($i = 0; $i < $fcount ; $i++)
{
$query .= $fields[$i];
if($i != ($fcount - 1)) // i = 0 that the first element in the array .. 2 will be - 1 last 3shan hwa by3ed el array mn wa7ed :D
$query .=' , ';
}
$query .= ' WHERE `id` = '.$id;
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
else
return true;
}
include ('db.php') ;
error_reporting(E_ALL);
ini_set('display_errors', 1);
$result = tinyf_users_update(6,'ggrgrgr','123456',NULL,0);
if($result) //($uid,$name = NULL,$password = NULL ,$email = NULL,$isadmin = 0)
echo 'success';
?>
you have 2 options
remove require_once('db.php'); from your main file, since you already include it in usersAPI.php
remove require_once('db.php'); from your usersAPI.php if you plan to include both db.php and usersAPI.php together

Input type submit login error

Ok, so I have downloaded mibew messenger and I want to customize the buttons, so I go into login.php and the actual submit button for the login is type="image" so I changed to to type="submit" and when I submit the form I get a incorrect username/password error, anyway I was very confused so I was looking through loads of the other files to see if I can find anything that's related to the type="image" just in-case there's something that identifies the type="image", well I dunno, I didn't find anything but what I did notice is that when I type in admin into the username and click login the submit button it returns the login error but also in the box where I put admin there is now the value of the type="submit" so in this case it says login because the value is value="login", I'm really confused, I think maybe it is submitting "login" instead of "admin" as the username.
Here is the before and after submit buttons:
NEW
<input type="submit" name="login" value="login" >
ORIGINAL
<input type="image" name="login" src='<?php echo $webimroot.getlocal("image.button.login") ?>' alt='<?php echo getlocal("button.enter") ?>'/>
If i change it back to the original it works fine, but i want to use css not images.
Also, it would be quite hard to make a jsfiddle, otherwise i would have made one.
This is login.php where is posts the data
require_once('../libs/common.php');
require_once('../libs/operator.php');
$errors = array();
$page = array('formisRemember' => true, 'version' => $version);
if (isset($_POST['login']) && isset($_POST['password'])) {
$login = getparam('login');
$password = getparam('password');
$remember = isset($_POST['isRemember']) && $_POST['isRemember'] == "on";
$operator = operator_by_login($login);
if ($operator && isset($operator['vcpassword']) && $operator['vcpassword'] == md5($password)) {
$target = isset($_SESSION['backpath'])
? $_SESSION['backpath']
: "$root/agent/index.php";
login_operator($operator, $remember);
header("Location: $target");
exit;
} else {
$errors[] = getlocal("page_login.error");
$page['formlogin'] = $login;
}
}
$page['localeLinks'] = get_locale_links("$root/agent/login.php");
start_html_output();
require('../display/login.php');
This is the included operator.php in login.php
$can_administrate = 0;
$can_takeover = 1;
$can_viewthreads = 2;
$can_modifyprofile = 3;
$can_count = 4;
$permission_ids = array(
$can_administrate => "admin",
$can_takeover => "takeover",
$can_viewthreads => "viewthreads",
$can_modifyprofile => "modifyprofile"
);
function operator_by_login($login)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vclogin = '" . mysql_real_escape_string($login) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_email($mail)
{
global $mysqlprefix;
$link = connect();
$operator = select_one_row(
"select * from ${mysqlprefix}chatoperator where vcemail = '" . mysql_real_escape_string($mail) . "'", $link);
mysql_close($link);
return $operator;
}
function operator_by_id_($id, $link)
{
global $mysqlprefix;
return select_one_row(
"select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function operator_by_id($id)
{
$link = connect();
$operator = operator_by_id_($id, $link);
mysql_close($link);
return $operator;
}
function operator_get_all()
{
global $mysqlprefix;
$link = connect();
$query = "select operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator order by vclogin";
$operators = select_multi_assoc($query, $link);
mysql_close($link);
return $operators;
}
function operator_is_online($operator)
{
global $settings;
return $operator['time'] < $settings['online_timeout'];
}
function operator_is_available($operator)
{
global $settings;
return $operator['istatus'] == 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function operator_is_away($operator)
{
global $settings;
return $operator['istatus'] != 0 && $operator['time'] < $settings['online_timeout'] ? "1" : "";
}
function update_operator($operatorid, $login, $email, $password, $localename, $commonname)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vclogin = '%s',%s vclocalename = '%s', vccommonname = '%s'" .
", vcemail = '%s', vcjabbername= '%s'" .
" where operatorid = %s",
mysql_real_escape_string($login),
($password ? " vcpassword='" . md5($password) . "'," : ""),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($email),
'',
$operatorid);
perform_query($query, $link);
mysql_close($link);
}
function update_operator_avatar($operatorid, $avatar)
{
global $mysqlprefix;
$link = connect();
$query = sprintf(
"update ${mysqlprefix}chatoperator set vcavatar = '%s' where operatorid = %s",
mysql_real_escape_string($avatar), $operatorid);
perform_query($query, $link);
mysql_close($link);
}
function create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link)
{
global $mysqlprefix;
$query = sprintf(
"insert into ${mysqlprefix}chatoperator (vclogin,vcpassword,vclocalename,vccommonname,vcavatar,vcemail,vcjabbername) values ('%s','%s','%s','%s','%s','%s','%s')",
mysql_real_escape_string($login),
md5($password),
mysql_real_escape_string($localename),
mysql_real_escape_string($commonname),
mysql_real_escape_string($avatar),
mysql_real_escape_string($email), '');
perform_query($query, $link);
$id = mysql_insert_id($link);
return select_one_row("select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
}
function create_operator($login, $email, $password, $localename, $commonname, $avatar)
{
$link = connect();
$newop = create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link);
mysql_close($link);
return $newop;
}
function notify_operator_alive($operatorid, $istatus)
{
global $mysqlprefix;
$link = connect();
perform_query("update ${mysqlprefix}chatoperator set istatus = $istatus, dtmlastvisited = CURRENT_TIMESTAMP where operatorid = $operatorid", $link);
mysql_close($link);
}
function has_online_operators($groupid = "")
{
global $settings, $mysqlprefix;
loadsettings();
$link = connect();
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time from ${mysqlprefix}chatoperator";
if ($groupid) {
$query .= ", ${mysqlprefix}chatgroupoperator where groupid = $groupid and ${mysqlprefix}chatoperator.operatorid = ${mysqlprefix}chatgroupoperator.operatorid and istatus = 0";
} else {
$query .= " where istatus = 0";
}
$row = select_one_row($query, $link);
mysql_close($link);
return $row['time'] < $settings['online_timeout'] && $row['total'] > 0;
}
function is_operator_online($operatorid, $link)
{
global $settings, $mysqlprefix;
loadsettings_($link);
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator where operatorid = $operatorid";
$row = select_one_row($query, $link);
return $row['time'] < $settings['online_timeout'] && $row['total'] == 1;
}
function get_operator_name($operator)
{
global $home_locale, $current_locale;
if ($home_locale == $current_locale)
return $operator['vclocalename'];
else
return $operator['vccommonname'];
}
function append_query($link, $pv)
{
$infix = '?';
if (strstr($link, $infix) !== FALSE)
$infix = '&';
return "$link$infix$pv";
}
function check_login($redirect = true)
{
global $root, $mysqlprefix;
if (!isset($_SESSION["${mysqlprefix}operator"])) {
if (isset($_COOKIE['webim_lite'])) {
list($login, $pwd) = preg_split("/,/", $_COOKIE['webim_lite'], 2);
$op = operator_by_login($login);
if ($op && isset($pwd) && isset($op['vcpassword']) && md5($op['vcpassword']) == $pwd) {
$_SESSION["${mysqlprefix}operator"] = $op;
return $op;
}
}
$requested = $_SERVER['PHP_SELF'];
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) {
$requested .= "?" . $_SERVER['QUERY_STRING'];
}
if ($redirect) {
$_SESSION['backpath'] = $requested;
header("Location: $root/agent/login.php");
exit;
} else {
return null;
}
}
return $_SESSION["${mysqlprefix}operator"];
}
function get_logged_in()
{
global $mysqlprefix;
return isset($_SESSION["${mysqlprefix}operator"]) ? $_SESSION["${mysqlprefix}operator"] : FALSE;
}
function login_operator($operator, $remember)
{
global $root, $mysqlprefix;
$_SESSION["${mysqlprefix}operator"] = $operator;
if ($remember) {
$value = $operator['vclogin'] . "," . md5($operator['vcpassword']);
setcookie('webim_lite', $value, time() + 60 * 60 * 24 * 1000, "$root/");
} else if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function logout_operator()
{
global $root, $mysqlprefix;
unset($_SESSION["${mysqlprefix}operator"]);
unset($_SESSION['backpath']);
if (isset($_COOKIE['webim_lite'])) {
setcookie('webim_lite', '', time() - 3600, "$root/");
}
}
function setup_redirect_links($threadid, $token)
{
global $page, $root, $settings, $mysqlprefix;
loadsettings();
$link = connect();
$operatorscount = db_rows_count("${mysqlprefix}chatoperator", array(), "", $link);
$groupscount = 0;
$groups = array();
if ($settings['enablegroups'] == "1") {
foreach (get_groups($link, true) as $group) {
if ($group['inumofagents'] == 0) {
continue;
}
$groups[] = $group;
}
$groupscount = count($groups);
}
prepare_pagination(max($operatorscount, $groupscount), 8);
$p = $page['pagination'];
$limit = $p['limit'];
$operators = select_multi_assoc(db_build_select(
"operatorid, vclogin, vclocalename, vccommonname, istatus, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time",
"${mysqlprefix}chatoperator", array(), "order by vclogin $limit"), $link);
$groups = array_slice($groups, $p['start'], $p['end'] - $p['start']);
mysql_close($link);
$agent_list = "";
$params = array('thread' => $threadid, 'token' => $token);
foreach ($operators as $agent) {
$params['nextAgent'] = $agent['operatorid'];
$status = $agent['time'] < $settings['online_timeout']
? ($agent['istatus'] == 0
? getlocal("char.redirect.operator.online_suff")
: getlocal("char.redirect.operator.away_suff")
)
: "";
$agent_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_operator_name($agent)) . "\">" .
topage(get_operator_name($agent)) .
"</a> $status</li>";
}
$page['redirectToAgent'] = $agent_list;
$group_list = "";
if ($settings['enablegroups'] == "1") {
$params = array('thread' => $threadid, 'token' => $token);
foreach ($groups as $group) {
$params['nextGroup'] = $group['groupid'];
$status = $group['ilastseen'] !== NULL && $group['ilastseen'] < $settings['online_timeout']
? getlocal("char.redirect.operator.online_suff")
: ($group['ilastseenaway'] !== NULL && $group['ilastseenaway'] < $settings['online_timeout']
? getlocal("char.redirect.operator.away_suff")
: "");
$group_list .= "<li><a href=\"" . add_params($root . "/agent/redirect.php", $params) .
"\" title=\"" . topage(get_group_name($group)) . "\">" .
topage(get_group_name($group)) .
"</a> $status</li>";
}
}
$page['redirectToGroup'] = $group_list;
}
$permission_list = array();
function get_permission_list()
{
global $permission_list, $permission_ids;
if (count($permission_list) == 0) {
foreach ($permission_ids as $permid) {
$permission_list[] = array(
'id' => $permid,
'descr' => getlocal("permission.$permid")
);
}
}
return $permission_list;
}
function is_capable($perm, $operator)
{
$permissions = $operator && isset($operator['iperm']) ? $operator['iperm'] : 0;
return $perm >= 0 && $perm < 32 && ($permissions & (1 << $perm)) != 0;
}
function prepare_menu($operator, $hasright = true)
{
global $page, $settings, $can_administrate;
$page['operator'] = topage(get_operator_name($operator));
if ($hasright) {
loadsettings();
$page['showban'] = $settings['enableban'] == "1";
$page['showgroups'] = $settings['enablegroups'] == "1";
$page['showstat'] = $settings['enablestatistics'] == "1";
$page['showadmin'] = is_capable($can_administrate, $operator);
$page['currentopid'] = $operator['operatorid'];
}
}
function get_all_groups($link)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_groups($link, $checkaway)
{
global $mysqlprefix;
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname, vclocaldescription" .
", (SELECT count(*) from ${mysqlprefix}chatgroupoperator where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid) as inumofagents" .
", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus = 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseen" .
($checkaway
? ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus <> 0 and ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseenaway"
: ""
) .
" from ${mysqlprefix}chatgroup order by vclocalname";
return select_multi_assoc($query, $link);
}
function get_operator_groupids($operatorid)
{
global $mysqlprefix;
$link = connect();
$query = "select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid";
$result = select_multi_assoc($query, $link);
mysql_close($link);
return $result;
}
And it wont let me add any more code if you need common.php let me know
Without seeing your PHP it's hard to tell, but it could be that image submits "login" as POST/GET variable value array(x, y), where the submit type will just a string value. If you are checking the submission based on that value, you will need to make some changes.
EDIT:
Looking at your code, it looks like you might be using 'login' as the username and the submit button. Try changing the submit button name to something else.
<input type="submit" name="loginButton" value="login" />

Categories