Put Mysql query result in array inside a class - php

Hello everybody again I'm tryin to resolve my issue poste in this topic -> Fetch data from Prestashop custom field
I've have made a MySql query outside my class and now it works but i need to put the result in an array inside the class. I paste my code below:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT codice_target FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id_customer"]. " - Codice target: " . $row["codice_target"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
Then there is the class and the function i need to put the result from the query
class AdvancedExport extends Module
{
//other methods here...
public function fputToFile($file, $allexportfields, $object, $ae)
{
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
// need to put mysql query result here inside $readyForExport['codice_target'];
$this->counter[$readyForExport['id_order']] = (!empty($this->counter[$readyForExport['id_order']])) ? ++$this->counter[$readyForExport['id_order']] : 1; // try here
$readyForExport['orderLine'] = $this->counter[$readyForExport['id_order']]; // and try here
//print_r('The id_order is added: ' . $readyForExport['orderLine']); // see if it is added
//echo '<pre>' . var_dump($readyForExport) . '</pre>';
// modifiche === Dario === prezzo
$newPrice = substr($readyForExport['product_price'], 0, strpos($readyForExport['product_price'], "."));
$readyForExport['product_price'] = $newPrice;
// === data
$newDateAdd = new DateTime($readyForExport['date_add']);
$readyForExport['date_add'] = $newDateAdd->format('d/m/Y');
// aggiungo 21 giorni - 3 settimane - alla data di acquisto
$date_mod = clone $newDateAdd;
$date_mod->add(new DateInterval('P21D'));
$readyForExport['delivery_date'] = $date_mod->format('d/m/Y');
// === data invoice
$newDateInvoice = clone $newDateAdd;
$readyForExport['invoice_date'] = $newDateAdd->format('d/m/Y');
//scambio l'id customer con il codice_target
//$readyForExport['codice_target'] = 8989;
$textTarget = (string)$readyForExport['codice_target'];
$readyForExport['id_customer'] = $textTarget;
// aggiungo gli zeri davanti al customer id
$id_count = strlen($readyForExport['id_customer']);
if ($id_count == 1) {
$newCustomer = "0000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 2) {
$newCustomer = "000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 3) {
$newCustomer = "00000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 4) {
$newCustomer = "0000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 5) {
$newCustomer = "000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 6) {
$newCustomer = "00".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}
// elaboro lo SKU
$textSku = (string)$readyForExport['product_name'];
$newSku_1 = $readyForExport['product_name'];
$newSku_1 = substr($newSku_1,0,4);
$newSku_2 = "/".substr($textSku,-4,4);
$newSku_tot = $newSku_1.$newSku_2;
$newSku_tot = str_replace(' ', '', $newSku_tot);
$newSku_tot = str_replace('-', '', $newSku_tot);
$newSku_tot = str_replace('co', '', $newSku_tot);
$newSku_tot = str_replace('e', '', $newSku_tot);
$newSku_tot = str_replace('r', '', $newSku_tot);
$readyForExport['product_name'] = $newSku_tot;
// aggiungo un campo fisso
$readyForExport['causale'] = "NR";
// aggiungo un campo fisso
$readyForExport['ORCL'] = "ORCL";
//$readyForExport['G'] = "";
$readyForExport['J'] = "";
$readyForExport['K'] = "";
$readyForExport['L'] = "";
$readyForExport['M'] = "";
$readyForExport['N'] = "";
$readyForExport['P'] = "";
$readyForExport['Q'] = "";
$readyForExport['R'] = "30";
$index_arr=array("id_customer","date_add","ORCL","product_name","causale","product_quantity","product_price","delivery_date","id_order","J","K","L","M","N","orderLine","P","Q","R");
//riordino i campi in base a come li dispongo nella variabile $index_arr
$arr_t=array();
foreach($index_arr as $i=>$v) {
foreach($readyForExport as $k=>$b) {
if ($k==$v) $arr_t[$k]=$b;
}
}
$readyForExport=$arr_t;
//write into csv line by line
fputcsv($file, $readyForExport, $ae->delimiter, $ae->separator);
}
}
Thanks far all done until now, Im really close to the goal.

Array values initialized to $rtoclass variable outside the class, then passed to an AdvancedExport object through its method - $obj->set_arr_needed( $rtoclass );
On $obj->fputToFile() call, the needed array will automatically be available for use inside it via the variable $arr_needed_in.
Try:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT codice_target FROM customer";
$result = $conn->query($sql);
$rtoclass = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id_customer"]. " - Codice target: " . $row["codice_target"]."<br>";
$rtoclass[] = $row;
}
} else {
echo "0 results";
}
$obj = new AdvancedExport();
$obj->set_arr_needed( $rtoclass );
$conn->close();
For the class:
class AdvancedExport extends Module
{
//other methods here...
private $arr_needed = array();
public function set_arr_needed( $arr ) {
$this->arr_needed = $arr;
}
public function get_arr_needed() {
return $this->arr_needed;
}
public function fputToFile($file, $allexportfields, $object, $ae)
{
$arr_needed_in = $this->get_arr_needed(); // array needed already inside..
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
// need to put mysql query result here inside $readyForExport['codice_target'];
$this->counter[$readyForExport['id_order']] = (!empty($this->counter[$readyForExport['id_order']])) ? ++$this->counter[$readyForExport['id_order']] : 1; // try here
$readyForExport['orderLine'] = $this->counter[$readyForExport['id_order']]; // and try here
//print_r('The id_order is added: ' . $readyForExport['orderLine']); // see if it is added
//echo '<pre>' . var_dump($readyForExport) . '</pre>';
// modifiche === Dario === prezzo
$newPrice = substr($readyForExport['product_price'], 0, strpos($readyForExport['product_price'], "."));
$readyForExport['product_price'] = $newPrice;
// === data
$newDateAdd = new DateTime($readyForExport['date_add']);
$readyForExport['date_add'] = $newDateAdd->format('d/m/Y');
// aggiungo 21 giorni - 3 settimane - alla data di acquisto
$date_mod = clone $newDateAdd;
$date_mod->add(new DateInterval('P21D'));
$readyForExport['delivery_date'] = $date_mod->format('d/m/Y');
// === data invoice
$newDateInvoice = clone $newDateAdd;
$readyForExport['invoice_date'] = $newDateAdd->format('d/m/Y');
//scambio l'id customer con il codice_target
//$readyForExport['codice_target'] = 8989;
$textTarget = (string)$readyForExport['codice_target'];
$readyForExport['id_customer'] = $textTarget;
// aggiungo gli zeri davanti al customer id
$id_count = strlen($readyForExport['id_customer']);
if ($id_count == 1) {
$newCustomer = "0000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 2) {
$newCustomer = "000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 3) {
$newCustomer = "00000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 4) {
$newCustomer = "0000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 5) {
$newCustomer = "000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 6) {
$newCustomer = "00".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}
// elaboro lo SKU
$textSku = (string)$readyForExport['product_name'];
$newSku_1 = $readyForExport['product_name'];
$newSku_1 = substr($newSku_1,0,4);
$newSku_2 = "/".substr($textSku,-4,4);
$newSku_tot = $newSku_1.$newSku_2;
$newSku_tot = str_replace(' ', '', $newSku_tot);
$newSku_tot = str_replace('-', '', $newSku_tot);
$newSku_tot = str_replace('co', '', $newSku_tot);
$newSku_tot = str_replace('e', '', $newSku_tot);
$newSku_tot = str_replace('r', '', $newSku_tot);
$readyForExport['product_name'] = $newSku_tot;
// aggiungo un campo fisso
$readyForExport['causale'] = "NR";
// aggiungo un campo fisso
$readyForExport['ORCL'] = "ORCL";
//$readyForExport['G'] = "";
$readyForExport['J'] = "";
$readyForExport['K'] = "";
$readyForExport['L'] = "";
$readyForExport['M'] = "";
$readyForExport['N'] = "";
$readyForExport['P'] = "";
$readyForExport['Q'] = "";
$readyForExport['R'] = "30";
$index_arr=array("id_customer","date_add","ORCL","product_name","causale","product_quantity","product_price","delivery_date","id_order","J","K","L","M","N","orderLine","P","Q","R");
//riordino i campi in base a come li dispongo nella variabile $index_arr
$arr_t=array();
foreach($index_arr as $i=>$v) {
foreach($readyForExport as $k=>$b) {
if ($k==$v) $arr_t[$k]=$b;
}
}
$readyForExport=$arr_t;
//write into csv line by line
fputcsv($file, $readyForExport, $ae->delimiter, $ae->separator);
}
}
}

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

php socket server closing port after 24h

i have a php socket server but i'm facing problems.
I have a tracker socket system, where the tracker connects to my server and send data. The server get this data and store into a database.
I'm using xampp for windows and the server is using port 8080.
My problem is that after 24h of job the port 8080 just block all connections, even the connections that are already connected to server.
I have tried all but nothing is helping me, because after 24 hours server stops port 8080.
It's important to say that xampp didn't show any error when port stops and the php page still running.
Please, can someone help me fix this problem?
My code:
$servername = "xxx.xxx.xxx.xxx";
$username = "username";
$password = "pass";
$dbname = "dbname";
$ip_address = "my_machine_ip";
$port = "8080";
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors',1);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// open a server on port 8080
$server = stream_socket_server("tcp://$ip_address:$port", $errno, $errorMessage);
if ($server === false) {
die("stream_socket_server error: $errorMessage");
}
$client_sockets = array();
$ativos = array();
while (true) {
// prepare readable sockets
$read_sockets = $client_sockets;
$read_sockets[] = $server;
// start reading and use a large timeout
if(!stream_select($read_sockets, $write, $except, 30000)) {
die('stream_select error.');
}
// new client
if(in_array($server, $read_sockets)) {
$new_client = stream_socket_accept($server);
if($new_client != ""){
array_push($ativos, $new_client);
}
echo count($ativos);
if ($new_client) {
//print remote client information, ip and port number
echo 'new connection: ' . stream_socket_get_name($new_client, true) . "<br>";
$client_sockets[] = $new_client;
echo "total clients: ". count($client_sockets) . "<br>";
// $output = "hello new client.\n";
// fwrite($new_client, $output);
}
//delete the server socket from the read sockets
unset($read_sockets[ array_search($server, $read_sockets) ]);
}
// message from existing client
foreach ($read_sockets as $socket) {
$data = fread($socket, 1024); //original is $data = fread($socket, 128); but is freezing port after 30 connections in the same time.
echo "data: " . $data . "<br>";
$tk103_data = explode( ',', $data);
$response = "";
switch (count($tk103_data)) {
case 1: // 359710049095095 -> heartbeat requires "ON" response
$response = "ON";
echo "Enviado ON para o Client $tk103_data[0]!<br>";
break;
case 3: // ##,imei:359710049095095,A -> this requires a "LOAD" response
if ($tk103_data[0] == "##") {
$response = "LOAD";
echo "Enviado LOAD para o Client $tk103_data[1]!<br>";
}
break;
case 7: //868683028738833,O,latitude1,longitude1,latitude2,longitude2;
if($tk103_data[0] == "**"){
$imeiCerca = $tk103_data[1];
$lat1 = $tk103_data[3];
$lng1 = $tk103_data[4];
$lat2 = $tk103_data[5];
$lng2 = $tk103_data[6];
$response2 = "**,imei:$imeiCerca,O,$lat1,$lng1,$lat2,$lng2";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
}
break;
case 13: //imei:868683028738833,tracker,170627204932,,F,124929.000,A,0925.3265,S,04029.8821,W,0.00,0;
$new_imei = str_replace("imei:", "", "$tk103_data[0]");
$new_imei = substr($new_imei, 0, 15);
if ($tk103_data[1] != "" && $tk103_data[4] != "L" && $tk103_data[5] != "" && $tk103_data[6] !="" && $tk103_data[8] != "" && $tk103_data[10] != "") {
$str = $tk103_data[2];
$arr2 = str_split($str, 2);
$dia = $arr2[2];
$mes = $arr2[1];
$ano = $arr2[0];
$hora = $arr2[3];
$minuto = $arr2[4];
$sqlChecker = "SELECT id, comando, latitude, longitude, status FROM gps_data_single WHERE imei='$new_imei' ORDER BY id DESC LIMIT 1";
$resultChecker = $conn->query($sqlChecker);
if ($resultChecker->num_rows > 0) {
while($rowChecker = $resultChecker->fetch_assoc()) {
$id = $rowChecker["id"];
$comando = $rowChecker["comando"];
$lat = $rowChecker["latitude"];
$long = $rowChecker["longitude"];
$st = $rowChecker["status"];
$estatus = explode(";", $st);
if($comando==$tk103_data[1] && $lat==$tk103_data[7] && $long==$tk103_data[9] && $st==$tk103_data[12]){
echo "Continua o mesmo Comando e Posição! Dados não salvos!<br>";
}else{
$sqla = "INSERT INTO gps_data_single (imei, comando, datetime, numerotel, gps_sinal, full_hour, sinal_gps, latitude, lat_orientacao, longitude, long_orientacao, speed, status, dia, mes, ano, hora, minuto) VALUES ('$new_imei', '$tk103_data[1]', '$str', '$tk103_data[3]', '$tk103_data[4]', '$tk103_data[5]', '$tk103_data[6]', '$tk103_data[7]', '$tk103_data[8]', '$tk103_data[9]', '$tk103_data[10]', '$tk103_data[11]', '$estatus[0];', '$dia', '$mes', '$ano', '$hora', '$minuto')";
if ($conn->query($sqla) === TRUE) {
echo "Inserido na Base!<br>";
} else {
echo "Error: " . $sqla . "<br>" . $conn->error;
}
}
}
}
}
if ($tk103_data[1] == "tracker"){
//Bloquear pela Chave
$sqlHp = "SELECT id, minuto FROM gps_data_single WHERE imei='$new_imei' AND comando='help me' ORDER BY id DESC LIMIT 1";
$resultHp = $conn->query($sqlHp);
if ($resultHp->num_rows > 0) {
// output data of each row
while($rowHp = $resultHp->fetch_assoc()) {
$id = $rowHp["id"];
$time = $rowHp["minuto"];
$mnow = date("i");
$time2 = $time + 5;
if($mnow >= $time2){
$response = "**,imei:$new_imei,J";
echo "Enviado o código $response para o cliente!<br>";
$sqlUHp = "UPDATE gps_data_single SET comando='help' WHERE id='$id'";
if ($conn->query($sqlUHp) === TRUE) {
echo "Trocado o help me pelo helpme! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
}
//Armar pelo Browser
if ($tk103_data[1] == "armcar"){
$response2 = "**,imei:$new_imei,L";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlArm = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='armcar' ORDER BY id DESC LIMIT 1";
$resultArm = $conn->query($sqlArm);
if ($resultArm->num_rows > 0) {
// output data of each row
while($rowArm = $resultArm->fetch_assoc()) {
$idArm = $rowArm["id"];
$sqlUArm = "DELETE FROM gps_data_single WHERE id='$idArm'";
if ($conn->query($sqlUArm) === TRUE) {
echo "Apagado o pedido de armar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Desarmar pelo Browser
if ($tk103_data[1] == "disarmcar"){
$response2 = "**,imei:$new_imei,M";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlDArm = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='disarmcar' ORDER BY id DESC LIMIT 1";
$resultDArm = $conn->query($sqlDArm);
if ($resultDArm->num_rows > 0) {
// output data of each row
while($rowDArm = $resultDArm->fetch_assoc()) {
$idDArm = $rowDArm["id"];
$sqlUDArm = "DELETE FROM gps_data_single WHERE id='$idDArm'";
if ($conn->query($sqlUDArm) === TRUE) {
echo "Apagado o pedido de armar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Bloquear pelo Browser
if ($tk103_data[1] == "cut"){
$response2 = "**,imei:$new_imei,J";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlCut = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='cut' ORDER BY id DESC LIMIT 1";
$resultCut = $conn->query($sqlCut);
if ($resultCut->num_rows > 0) {
// output data of each row
while($rowCut = $resultCut->fetch_assoc()) {
$idCut = $rowCut["id"];
$sqlUCut = "UPDATE gps_data_single SET comando='help' WHERE id='$idCut'";
if ($conn->query($sqlUCut) === TRUE) {
echo "Atualizado o pedido de bloqeuar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Retornar pelo Browser
if ($tk103_data[1] == "resume"){
$response2 = "**,imei:$new_imei,K";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlResume = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='resume' ORDER BY id DESC LIMIT 1";
$resultResume = $conn->query($sqlResume);
if ($resultResume->num_rows > 0) {
// output data of each row
while($rowResume = $resultResume->fetch_assoc()) {
$idResume = $rowResume["id"];
$sqlUResume = "DELETE FROM gps_data_single WHERE id='$idResume'";
if ($conn->query($sqlUResume) === TRUE) {
echo "Apagado o pedido de religar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Velocidade pelo Browser
if ($tk103_data[1] == "myspeed"){
$sqlVel = "SELECT id, speed FROM gps_data_single WHERE imei='$new_imei' AND comando='myspeed' ORDER BY id DESC LIMIT 1";
$resultVel = $conn->query($sqlVel);
if ($resultVel->num_rows > 0) {
// output data of each row
while($rowVel = $resultVel->fetch_assoc()) {
$idVel = $rowVel["id"];
$maxVel = $rowVel["speed"];
if($maxVel<100){
$maxVel = "0$maxVel";
}
$response2 = "**,imei:$new_imei,H,$maxVel";
echo "Enviado o código $response2 para o cliente!<br>";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlUVel = "DELETE FROM gps_data_single WHERE id='$idVel'";
if ($conn->query($sqlUVel) === TRUE) {
echo "Atualizado velocidade pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Remover Cerca
if ($tk103_data[1] == "removefence"){
$sqlRemFen = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='removefence' ORDER BY id DESC LIMIT 1";
$resultRemFen = $conn->query($sqlRemFen);
if ($resultRemFen->num_rows > 0) {
// output data of each row
while($rowRemFen = $resultRemFen->fetch_assoc()) {
$idRemFen = $rowRemFen["id"];
}
$response2 = "**,imei:$new_imei,P";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlURemFen = "DELETE FROM gps_data_single WHERE id='$idRemFen'";
if ($conn->query($sqlURemFen) === TRUE) {
echo "Removido a cerca pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
//Alarme de Porta
if ($tk103_data[1] == "door alarm"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlPush = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush = $conn->query($sqlPush);
if ($resultPush->num_rows > 0) {
// output data of each row
while($rowPush = $resultPush->fetch_assoc()) {
$push1 = $rowPush["usr"];
$placa1 = $rowPush["placa_veiculo"];
// Push The notification with parameters
if($push1!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push1);
// Notification Settings
$pb->Alert("Porta do veículo $placa1 aberta sem autorização!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Porta do veículo $placa1 aberta sem autorização em $dia/$mes/$ano às $hora:$minuto!', '$push1', '3')";
if ($conn->query($sqlNot) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alarme Veículo Ligado
if ($tk103_data[1] == "acc alarm" || $tk103_data[1] == "ac alarm" && $tk103_data[4] != "L"){
$sqlPush1 = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush1 = $conn->query($sqlPush1);
if ($resultPush1->num_rows > 0) {
// output data of each row
while($rowPush1 = $resultPush1->fetch_assoc()) {
$push2 = $rowPush1["usr"];
$placa2 = $rowPush1["placa_veiculo"];
// Push The notification with parameters
if($push2!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push2);
// Notification Settings
$pb->Alert("Veículo $placa2 ligado sem autorização!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot2 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa2 ligado sem autorização em $dia/$mes/$ano às $hora:$minuto!', '$push2', '3')";
if ($conn->query($sqlNot2) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alerta Velocidade
if ($tk103_data[1] == "speed"){
$sqlPush5 = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush5 = $conn->query($sqlPush5);
if ($resultPush5->num_rows > 0) {
// output data of each row
while($rowPush5 = $resultPush5->fetch_assoc()) {
$push5 = $rowPush5["usr"];
$placa5 = $rowPush5["placa_veiculo"];
// Push The notification with parameters
if($push5!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push5);
// Notification Settings
$pb->Alert("Veículo $placa5 atingiu a velocidade máxima!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot5 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa5 atingiu a velocidade máxima em $dia/$mes/$ano às $hora:$minuto!', '$push5', '3')";
if ($conn->query($sqlNot5) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alerta Fora da Cerca
if ($tk103_data[1] == "stockade"){
$sqlPushSt = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPushSt = $conn->query($sqlPushSt);
if ($resultPushSt->num_rows > 0) {
// output data of each row
while($rowPushSt = $resultPushSt->fetch_assoc()) {
$pushSt = $rowPushSt["usr"];
$placaSt = $rowPushSt["placa_veiculo"];
// Push The notification with parameters
if($pushSt!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($pushSt);
// Notification Settings
$pb->Alert("Veículo $placaSt saiu da cerca definida!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNotSt = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placaSt saiu da cerca definida no $dia/$mes/$ano às $hora:$minuto!', '$pushSt', '3')";
if ($conn->query($sqlNotSt) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alarme de Vibração
if ($tk103_data[1] == "sensor alarm"){
$sqlPushSen = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPushSen = $conn->query($sqlPushSen);
if ($resultPushSen->num_rows > 0) {
// output data of each row
while($rowPushSen = $resultPushSen->fetch_assoc()) {
$push1Sen = $rowPushSen["usr"];
$placa1Sen = $rowPushSen["placa_veiculo"];
// Push The notification with parameters
if($push1Sen!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push1Sen);
// Notification Settings
$pb->Alert("Veículo $placa1Sen detectou uma forte vibração!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNotPush = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa1Sen detectou uma forte vibração em $dia/$mes/$ano às $hora:$minuto!', '$push1Sen', '3')";
if ($conn->query($sqlNotPush) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
if ($tk103_data[1] == "acc on"){
$response = "**,imei:$new_imei,C,03m";
echo "Enviado o código $response para o cliente!<br>";
}
if ($tk103_data[1] == "acc off"){
$response = "**,imei:$new_imei,C,60m";
echo "Enviado o código $response para o cliente!<br>";
}
if($tk103_data[1] == "help me"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlPush3 = "SELECT usr FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush3 = $conn->query($sqlPush3);
if ($resultPush3->num_rows > 0) {
// output data of each row
while($rowPush3 = $resultPush3->fetch_assoc()) {
$push3 = $rowPush3["usr"];
$sqlNot3 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Pedido de Bloqueio registrado no $dia/$mes/$ano às $hora:$minuto!', '$push3', '3')";
if ($conn->query($sqlNot3) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
if ($tk103_data[1] == "jt"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlD = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='jt'";
if ($conn->query($sqlD) === TRUE) {
echo "Deletado com sucesso o JT<br>";
}
}
if ($tk103_data[1] == "et"){
$sqlDe = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='et'";
if ($conn->query($sqlDe) === TRUE) {
echo "Deletado com sucesso o ET<br>";
}
}
if ($tk103_data[1] == "kt"){
$sqlDel = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='kt'";
if ($conn->query($sqlDel) === TRUE) {
echo "Deletado com sucesso o KT<br>";
}
}
if ($tk103_data[1] == "lt"){
$sqlDele = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='lt'";
if ($conn->query($sqlDele) === TRUE) {
echo "Deletado com sucesso o LT<br>";
}
}
if ($tk103_data[1] == "mt"){
$sqlDelet = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='mt'";
if ($conn->query($sqlDelet) === TRUE) {
echo "Deletado com sucesso o MT<br>";
}
}
if ($tk103_data[1] == "ht"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='ht'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o HT<br>";
}
}
if ($tk103_data[1] == "ot"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='ot'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o OT<br>";
}
}
if ($tk103_data[1] == "pt"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='pt'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o PT<br>";
}
}
break;
}
if (!$data) {
unset($client_sockets[ array_search($socket, $client_sockets) ]);
#fclose($socket);
echo "client $socket disconnected. total clients: ". count($client_sockets) . "\n";
continue;
}
//send the message back to client
if (sizeof($response) > 0) {
fwrite($socket, $response);
}
}
} // end while loop
$conn->close();
?>`

issue in student data updation

I have a table of student details. and i have two csv files,these files contains updated information of existing students and new students data.if data not in student table which means the student left the school.
update new details for existing students
If student left school update status the to zero
If new student,then add as new row(with details from both csv)
Below is my code but in this second file information not getting updated.
i am attaching my code.if anybody have simple solution,please suggest
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$sql = "SELECT * FROM e_student";
$result_main = $conn->query($sql);
$filea = $_FILES['filea'];
$ext = pathinfo($_FILES['filea']['name'], PATHINFO_EXTENSION);
if ($ext == "csv" && $_FILES["filea"]["error"] == 0) {
$target = "upload/" . $_FILES["filea"]["name"];
move_uploaded_file($_FILES["filea"]["tmp_name"], $target);
if (($handle = fopen($target, "r")) !== FALSE) {
$array = $fields = array();
$i = 0;
while (($row = fgetcsv($handle, 4096)) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k => $value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
fclose($handle);
}
}
$ext1 = pathinfo($_FILES['fileb']['name'], PATHINFO_EXTENSION);
if ($ext1 == "csv" && $_FILES["fileb"]["error"] == 0) {
$target1 = "upload/" . $_FILES["fileb"]["name"];
move_uploaded_file($_FILES["fileb"]["tmp_name"], $target1);
if (($handle = fopen($target1, "r")) !== FALSE) {
$array1 = $fields1 = array();
$j = 0;
while (($row1 = fgetcsv($handle, 4096)) !== false) {
if (empty($fields1)) {
$fields1 = $row1;
continue;
}
foreach ($row1 as $k => $value) {
$array1[$j][$fields1[$k]] = $value;
}
$j++;
}
fclose($handle);
}
}
foreach ($result_main as $rel) {
$clk = 'no';
foreach ($array as $arr) {
if(isset($arr1['SCD']))
{
if (strcmp(trim($rel['objId']), trim($arr['BCEID'])) == 0) {
$clk = 'yes';
$name = $arr['FirstName'];
$conditn = $rel['objId'];
$last_name = $arr['LegalSurname'];
$year_level = $arr['YearLevelName'];
$email = $arr['BCEEmail'];
$username = $arr['BCELogin'];
$StEnrollmentStatus = 1;
$sql1 = "UPDATE e_student SET Name = '$name',Lastname='$last_name',stYearLevel='$year_level',email='$email',username='$username' WHERE objId ='$conditn'";
$result = $conn->query($sql1);
if($result)
{
updateparent($rel['objId'], $array1,$conn);
}
}
}
}
if ($clk == 'no') {
$conditn = $rel['objId'];
$status = 0;
$pastoral = "Not Currently Enrolled";
$sql1 = "UPDATE e_student SET stEnrollmentStatus = '$status',stPastoral='$pastoral' WHERE objId ='$conditn'";
$result = $conn->query($sql1);
}
}
foreach ($array as $ar1) {
foreach ($result_main as $rel1) {
if (strcmp(trim($ar1['BCEID']), trim($rel1['objId'])) != 0) {
$name = $ar1['FirstName'];
$last_name = $ar1['LegalSurname'];
$year_level = $ar1['YearLevelName'];
$email = $ar1['BCEEmail'];
$objid = $ar1['BCEID'];
$username = $ar1['BCELogin'];
$StEnrollmentStatus = 1;
$sql3 = "INSERT INTO e_student(Name,Lastname,stYearLevel,email,objId,username,stEnrollmentStatus) VALUES('$name','$last_name','$year_level','$email','$objid','$username','$StEnrollmentStatus')";
$result1 = $conn->query($sql3);
if($result1)
{
updateparent1($objid, $array1,$conn);
}
}
}
}
echo "<h3><center>SUCCESSFULLY UPDATED</center></h3>";
}
function updateparent($objid, $array1,$conn) {
foreach ($array1 as $arr1) {
if(isset($arr1['SCD']))
{
if (strcmp(trim($objid), trim($arr1['SCD'])) == 0) {
$parent = $arr1['PTI1'] . $arr1['PFN1'] . $arr1['PSN1'];
echo $parent;
$email = $arr1['PEM1'];
}
$sql2 = "UPDATE e_student SET stParentName = '$parent',stParentEmail='$email' WHERE objId ='$objid'";
$result = $conn->query($sql2);
}
}
}
function updateparent1($objid, $array1,$conn) {
foreach ($array1 as $arr1) {
if(isset($arr1['SCD']))
{
echo $arr1['SCD'];
if (strcmp(trim($objid), trim($arr1['SCD'])) == 0) {
$parent = $arr1['PTI1'] . $arr1['PFN1'] . $arr1['PSN1'];
$email = $arr1['PEM1'];
}
$sql2 = "UPDATE e_student SET stParentName = '$parent',stParentEmail='$email' WHERE objId ='$objid'";
$result = $conn->query($sql2);
}
}
}
?>

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

Entering data twice

I made a php code for insert data on mysql.
if(isset($_POST['submitted'])){
$img = NULL;
if(isset($_FILES['upload'])){
include('classes/imagens.class.php');
$imagem = new imagem($_FILES['upload']['name'],$_FILES['upload']['tmp_name'],$_FILES['upload']['size'],$_FILES['upload']['error']);
if($imagem->verifica_extensao($_FILES['upload']['type']) && $imagem->verifica_tamanho()){
$erro = $imagem->upload();
$img = $imagem->getNome();
}
}
$trimmed = array_map('trim', $_POST); // usa a função trim() em todas as variáveis POST
$tit = $cat = $dat = $end = $des = $pr = $dono = $hor = FALSE; // atribui falso para as variaveis que poderão receber as variaveis POST
$mysql = new mysql('eventos');
if(!empty($trimmed['nome'])){
$tit = $mysql->escape_string($trimmed['nome']);
}
if(!empty($trimmed['categoria'])){
$cat = $mysql->escape_string($trimmed['categoria']);
}
if(!empty($trimmed['data'])){
$dat = $mysql->escape_string($trimmed['data']);
}
if($trimmed['hora'] != '--' && $trimmed['minuto'] != '--'){
$hor = $trimmed['hora'].":".$trimmed['minuto'];
$hor = $mysql->escape_string($hor);
}
if(!empty($trimmed['endereco'])){
$end = $mysql->escape_string($trimmed['endereco']);
}
if(!empty($trimmed['descricao'])){
$des = $mysql->escape_string($trimmed['descricao']);
}
if(!empty($trimmed['preco'])){
$pr = $mysql->escape_string($trimmed['preco']);
}
$dono = $_SESSION['user_id'];
if($tit && $cat && $dat && $end && $des && $pr && $dono && $hor){
$evento = new evento($tit, $cat, $end, $dat, $hor, $des, $pr, NULL, NULL, $img,$dono, NULL, NULL);
$evento->cadastrar();
echo '<h3>Evento cadastrado com sucesso!</h3>';
echo "<h1>Clique aqui para voltar para a página inicial</h1>";
exit();
}
}
and my function cadastrar()
function cadastrar(){
$this->mysql->sql("INSERT INTO eventos (nome, categoria, data, endereco, descricao,ref_imagem,preco,user_id, hora, data_registro) VALUES ('$this->Titulo','$this->Categoria','$this->Data','$this->Endereco','$this->Descricao','$this->RefImagem','$this->Preco','$this->Dono','$this->Horario',NOW())");
}
and my function sql()
function sql($query){
$this->connect();
$this->query = $query;
if(mysqli_query($this->dbc,$this->query)){
$linhas_afetadas = mysqli_affected_rows($this->dbc);
echo $query;
$this->result=mysqli_query($this->dbc,$this->query);
$this->disconnect();
$retorno = array($this->result,$linhas_afetadas);
return $retorno;
} else {
die("Ocorreu um erro ao executar a Query SQL abaixo:<br>$query");
$this->disconnect();
}
}
and... the result is 2 same columns on the table.
Every time you call mysqli_query, a query is launched to the database. You are doing that twice:
if (mysqli_query(...))
{
....
$this->result = mysqli_query(...);
}
So that's why you end with duplicated data.

Categories