Entering data twice - php

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.

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

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

Can't record script time correctly

I have an script that sometimes takes more than 40 seconds to run. But the microtime thing returns less thatn 1 second.
First issue is WHY IS THIS TAKING SO LONG???? and second issue is why microtime don't return time correctly?
<?
$inicio = microtime(true);
session_start();
header('Content-Type: text/html; charset=utf-8');
include 'coneccion-base-mails.php';
include 'coneccion.php';
include 'funciones.php';
$id = $_POST["id"];
//recuperamos los datos del envio
$R = $mysqli->query("SELECT * FROM envios WHERE id=".$id."")->fetch_array();
$remitente = $R["remitente"];
$lista = $R["lista"];
$asunto = $R["asunto"];
$cuerpo = $R["cuerpo"];
$sustituto = $R["sustituto"];
$contactos = array();
//ahora creamos cargamos la lista
if($lista=="Todos"){
$result = $mysqli->query("SELECT * FROM listas WHERE usuario='".$_SESSION["usuario"]."'");
while($R = $result->fetch_array()){
$dato = array($R["nombre"],$R["apellido"],$R["mail"]);
array_push($contactos,$dato);
}
}
else{
$result = $mysqli->query("SELECT * FROM segmentos WHERE titulo='".$lista."' and usuario='".$_SESSION["usuario"]."'");
$R = $result->fetch_array();
$idsegmento = $R["id"];
$result = $mysqli->query("SELECT * FROM listasegmentos WHERE idsegmento=".$idsegmento."");
while($R = $result->fetch_array()){
$dato = array(nombreContacto($R["idcontacto"]),apellidoContacto($R["idcontacto"]),mailContacto($R["idcontacto"]));
array_push($contactos,$dato);
}
}
//ya tenemos los contactos,
//ahora los recorremos uno a uno, fijandonos si ya fue enviado ese mail, si fue enviado vamos al siguiente, sino lo mandamos y cortamos.
$total = count($contactos);
$mm = 0;
if( mailsEnviadosEstaHora() < $limiteMailsPorHora){
foreach($contactos as $contacto){
$nombre = $contacto[0];
$apellido = $contacto[1];
$mail = $contacto[2];
if(mailEnviado($mail)=="no"){
if(strpos($mail,";")===false){
enviarMail($nombre." ".$apellido." <".$mail.">",$mail,$nombre);
}
else{
$mails = explode(";",$mail);
$comp = "";
foreach($mails as $mailss){
if($comp == ""){
$comp = $nombre." ".$apellido." <".$mailss.">";
}
else{
$comp .= ",".$nombre." ".$apellido." <".$mailss.">";
}
}
enviarMail($comp,$mail,$nombre);
}
break;
}
else{
$mm++;
}
}
if($mm == $total){
$mysqli->query("UPDATE envios SET estado='enviada' WHERE id=".$id."");
echo "actualizar";
}
}
else{
//se llego al limite de mails por hora
echo "limite";
}
function marcarEnviado($mail){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $mm;
global $total;
global $inicio;
$fecha = date("Y")."-".date("m")."-".date("d");
$mysqli->query("INSERT INTO procesoenvio (idenvio,destinatario,estado,fecha,hora,solohora) VALUES (".$id.",'".$mail."','enviado','".$fecha."','".date('H:i:s')."','".date('H')."')");
$caca = $mm+1;
echo $caca." / ".$total;
$actual = microtime(true);
$totalsss= $actual- $inicio;
echo 'Tiempo : '.$totalsss.' segundos<br>';
}
function enviarMail($para,$mail,$nombre){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $sustituto;
if($nombre==''){
$nombre = $sustituto;
}
//from
$from = array();
$_datos = explode("<",$remitente);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$from[$_mail] = $_nombre;
$cuentas = explode("---",$_SESSION['correo']);
foreach($cuentas as $cuenta){
$correo = explode("|||",$cuenta);
$username = $correo[0];
$password = $correo[1];
if($username == $_mail){
break;
}
}
//
require_once 'swiftmailer-master/lib/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SmtpTransport::newInstance("mail.dxxxxxxxxxxx.com",25);
$transport->setUsername($username);
$transport->setPassword($password);
// Create the message
$message = Swift_Message::newInstance();
$destinatarios = explode(",",$para);
$destin = array();
foreach($destinatarios as $destinatario){
$s = strpos($destinatario,"<");
if($s===false){
array_push($destin,$destinatario);
}
else{
$_datos = explode("<",$destinatario);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$destin[$_mail] = $_nombre;
}
}
$message->setTo($destin);
$message->setSubject($asunto);
$message->setFrom($from);
// adjuntos!!!
$ruta = '../../panel/envios/adjuntos/' . $id . '/'; // Relative to the root
if(file_exists($ruta)){ // Abrir archivos
$n = 0;
$archivos = array();
foreach (new DirectoryIterator($ruta) as $file) {
if($file->isDot()) continue;
array_push($archivos,$file->getFilename());
}
sort($archivos);
foreach($archivos as $archivo){
$message->attach(Swift_Attachment::fromPath('http://xxxxxxxxxxxxxxxxxxxx.com'.str_replace('../../','/',$ruta).str_replace(' ','-',$archivo)));
$n+=1;
//break;
}
if($n==0){
//no hay fotos en la carpeta
}
}
$cuerpoPersonalizado = str_replace('[[[Nombre]]]',$nombre,$cuerpo);
$message->setBody($cuerpoPersonalizado,'text/html');
$msg = $message->toString();
$msg = str_replace('http://xxxxxxxxxxxx.com/img.php?i','#',$msg);
$verificacion = base64_encode($id.'|||'.$mail);
$cuerpoPersonalizado = str_replace('numeroidentificacion',$verificacion,$cuerpoPersonalizado);
$message->setBody($cuerpoPersonalizado,'text/html');
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
//$mailer->send($message) or die($msg);
$mailer->send($message);
marcarEnviado($mail);
$hostname = '{localhost:143}Sent Items';
$conn = imap_open($hostname,$username,$password) or die('No se pudo conectar con: usuario: '.$username.' y clave: '.$password.' ' . imap_last_error());
imap_append($conn, '{localhost:143}Sent Items', $msg, "\\Seen") or die("error");
}
?>
As an important tangent to your question, please ensure you cleanse your data - those $_POSTs are wide open for SQL injection:
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Think about using PDO prepared statements. It's more secure (helps prepare statements against SQL injection) and makes transactions easy (for several repeated queries).
As for your answer, I think you are misunderstanding what microtime() returns. I've included a link to format the number of microseconds in the way you may expect.
php microtime() format value

Alfresco "admin" password keeps getting deleted when i call the same webscript multiple times

I've got a weird problem. I've created a procedure in PHP that does these things:
Read data (9.000 rows) from a MySQL table
Writes a row to another table
Create a folder in Alfresco based on a field in the row
I've got this strange problem (only on one Alfresco installation, on others I don't have the problem), after the first 2-3 rows the password for the admin user gets deleted from Alfresco (if you look in the db, you can't find it) and so the procedure stops. I'm using Alfresco Community 3.2.
Here is the PHP code of the procedure:
require_once("../components/com_astra/libs/AlfrescoConnect.php");
require_once("../components/com_astra/libs/FirePHPCore/fb.php");
$username = "***";
$password = "****;";
$hostname = "localhost";
ob_start();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("lbs_8",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT count(*) as quanti FROM ast_tabellaTemporaneaNdg");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
$totaleTabella = mysql_result($result, 0);
echo("La tabella ast_tabellaTemporaneaNdg contiene [$totaleTabella] records<br>");
echo("Conto il numero di record della vista di transcodifica<br>");
$result = mysql_query("SELECT count(*) as quanti FROM vista_ndg_normalizzati");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
$totaleVista = mysql_result($result, 0);
echo("La vista vista_ndg_normalizzati contiene [$totaleVista] records<br>");
if ($totaleTabella == $totaleVista){
echo("Tutte le righe della tabella ast_tabellaTemporaneaNdg sono transcodificate correttamente<br>");
echo("Saranno quindi importati [$totaleTabella] records<br>");
}else{
echo("Non tutte le righe della tabella ast_tabellaTemporaneaNdg sono transcodificate correttamente<br>");
echo("nella tabella ast_tabellaTemporaneaNdg sono presenti [$totaleTabella] records, di questi solo [$totaleVista] transcodificano correttamente<br>");
$handle = fopen("ndgNonImportabili.txt", "w");
$result = mysql_query("SELECT ndg FROM ast_tabellaTemporaneaNdg WHERE ndg NOT IN (SELECT ndg from vista_ndg_normalizzati)");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
while ($row = mysql_fetch_assoc($result)){
$ndg = "NDG: ".$row["ndg"]."\n";
fwrite ($handle, $ndg);
}
fclose($handle);
echo("Gli NDG non importabili sono stati loggati nel file ndgNonImportabili.txt<br>");
//die("L'importazione avra' inizio solo quando tutti gli NDG saranno importabili. I motivi per cui un ndg non è importabile possono essere: incorenza fra Natura Giuridica 1 e natura giuridica 2, Incoerenza fra comune, Provincia e Regione<br>");
}
$result = mysql_query("SELECT * FROM vista_ndg_normalizzati");
//fb($result, 'risultati');
$handle = fopen("logImportazione.txt", "w");
while ($row = mysql_fetch_assoc($result)) {
$user = "admin";
$ndg = $row['ndg'];
$response = AlfrescoConnect::createNDG($ndg, $user);
$status = $response['esito'];
if($status == "OK"){
$ragioneSociale = mysql_real_escape_string($row['ragioneSociale']);
$query = "SET FOREIGN_KEY_CHECKS=0";
$resultSetKeys = mysql_query($query);
$query = "INSERT INTO ast_Cliente (idUtente, idNaturaGiuridica, idTipoSegmento, idRegione, idProvincia, idComune, ragioneSociale, ndg, idNaturaGiuridica2) VALUES ";
$query .= " (1, ".$row['idNaturaGiuridica'].", 2 , ".$row['idRegione'].", ".$row['idProvincia'].", ".$row['idComune'].", '".$ragioneSociale."', '".$ndg."', ".$row['idNaturaGiuridica2'].")";
//fb($query);
$resultInsert = mysql_query($query);
if (!$resultInsert) {
$messaggio = "Si è verificato un errore nell'importazione dell'ndg [$ndg]: [".mysql_error()."]\n";
}else{
$messaggio = "[$ndg] importato con successo\n";
}
fwrite ($handle, $messaggio);
}else{
$messaggio = "Si è verificato un errore nella creazione della cartella per l'ndg [$ndg] su alfresco. ERRORE: [".$response['motivazione']."]\n";
fwrite ($handle, $messaggio);
}
}
fclose($handle);
echo("importazione completata: i risultati dell'importazione sono stati salvati nel file logImportazione.txt");
?>
The folder is created by calling $response = AlfrescoConnect::createNDG($ndg, $user); where $ndg is the name of the folder and $user is the user who created it
Here is the code of AlfrescoConnect.php:
class AlfrescoConnect
{
static public $webscriptURL = "http://localhost:8080/alfresco/service";
static public $login = "/api/login";
static public $login_ticket = "/api/login/ticket";
static public $alfrescoPath = "http://localhost:8080";
static public $alfrescoContext = "/alfresco";
static public $upload_file_script = "/astra/upload";
static public $uploadFile = "/astra/uploaddoc";
static public $search_document = "/astra/cercadocumenti";
static public $createNDG = "/astra/creandg";
static public $createPEFPerNDG = "/astra/creapef";
static public $searchDocumentPerConfirm = "/astra/cercadocumentoperconferma";
static public $confirmDocument = "/astra/confermadocumenti";
static public $getPEF = "/astra/estraidatipef";
static public $updatePEF = "/astra/aggiornapef";
static public $documentCounter = "/astra/contadocumenti";
static public $userLogin = "/astra/creautente";
static public $cancella = "/astra/managedocumentversions";
static public $alfUsername = "admin";
static public $alfPassword = "admin";
static public $ticket = "";
static public $userTicket = "";
static public function Authenticate($username='') {
//fb($username);
if(strcmp($username,'')==0){
if (AlfrescoConnect::isAuthenticated()) return true;
$link = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$login."?u=".AlfrescoConnect::$alfUsername."&pw=".AlfrescoConnect::$alfPassword . "&noCache=" .time();
fb($link, "LINK");
}else{
AlfrescoConnect::$userTicket = AlfrescoConnect::CustomAuthentication($username);
return true;
}
try {
//perform a http/get request to get tiket
// Try to create a ticket
// If the ticket fails, it means that the username and/or password are wrong
$r= new HttpRequest($link, HttpRequest::METH_GET);
$r->send() ;
$http_response = $r->getResponseBody();fb($http_response, "RISPOSTA");
$pos1 = stripos($http_response, "<ticket>");
$pos2 = stripos($http_response, "</ticket>");
//ceck if token is returned
if ($pos1<0 | !is_int($pos1) || $pos2<0 | !is_int($pos2)) {
AlfrescoConnect::$ticket = "";
$returnValue = false;
} else {
$pos1 += 8;
$pos2 -= $pos1;
// clean the xml info
AlfrescoConnect::$ticket = substr($http_response, $pos1, $pos2);
$returnValue = true;
}
//fb(AlfrescoConnect::$ticket);
$_SESSION["ticket"] = AlfrescoConnect::$ticket;
return true;
}
catch (Exception $e) {
fb($e, "Eccezione");
AlfrescoConnect::$ticket = "";
$_SESSION["ticket"] = AlfrescoConnect::$ticket;
return $returnValue;
}
}
static public function isAuthenticated() {
if (!isset($_SESSION["ticket"])) return false;
$link = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$login_ticket."/".$_SESSION["ticket"]."?alf_ticket=".$_SESSION["ticket"]."&noCache=" .time();
fb($link, 'link in isauth');
try {
//perform a http/get request to get tiket
// Try to create a ticket
// If the ticket fails, it means that the username and/or password are wrong
$r= new HttpRequest($link, HttpRequest::METH_GET);
$r->send() ;
$http_response = $r->getResponseBody();
$pos1 = stripos($http_response, "<ticket>");
$pos2 = stripos($http_response, "</ticket>");
//ceck if token is returned
if ($pos1<0 | !is_int($pos1) || $pos2<0 | !is_int($pos2)) {
return false;
} else {
$pos1 += 8;
$pos2 -= $pos1;
// clean the xml info
if ($_SESSION["ticket"] == substr($http_response, $pos1, $pos2)) {
AlfrescoConnect::$ticket = $_SESSION["ticket"];
return true;
}
}
}
catch (Exception $e) {
return false;
}
}
static public function CustomAuthentication($username=''){
$url = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$userLogin;
if ($auth) {
if (!AlfrescoConnect::Authenticate()) return -1;
$url .= "?alf_ticket=".AlfrescoConnect::$ticket;
}
$parameter = array('username' => $username);
//
$response = AlfrescoConnect::Query($url, $parameter,HttpRequest::METH_POST,1,0);fb($url);fb($parameter);
fb($response,'custom authentication result');
return $response;
}
* perform query on alfresco webscripts
*
* #param string $url alfresco webscript url
* #param string $params parameter for the query
* #param string $meth metohod for http request HTTP_METH_POST/HTTP_METH_GET default HTTP_METH_POST
* #param boolean $auth set whether or not to need authentication
* #return mixed -1 for authentication faliure, -2 for query faliure
*/
static public function Query($url, $params, $meth = HTTP_METH_POST, $auth = 1, $decode = 1, $ticketUser='') {
//Aggiunto per evitare il caching
//fb($url, "Query url");
//fb($params, "Query params");
//print_r(debug_backtrace());
$nocache=time();
$params['nocache']=$nocache;
if ($auth) {
if(strcmp($ticketUser,'')==0){
if (!AlfrescoConnect::Authenticate()) return -1;
$params['alf_ticket'] = AlfrescoConnect::$ticket;
}
else{
$params['alf_ticket'] = $ticketUser;
}
}
fb($params,'param');
try {
//fb("invio della richiesta");
$url=$url."?nocache=$nocache";
$r= new HttpRequest($url, $meth);
$r->addQueryData($params);
$r->send() ;
fb($r);
$http_response = $r->getResponseBody();
fb($http_response);
if (!$decode) return $http_response;
$json = new Services_JSON();
return object2array($json->decode($http_response));
//return json_decode($http_response, true);
}
catch (Exception $e) {
return -2;
}
}
/**
* Azioni su Alfresco
*
*/
static public function createNDG($ndg, $user){
$url = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$createNDG;
fb("Crea l'ndg,$url");
if (strcmp($user,'')!=0) {
$ticket = AlfrescoConnect::Authenticate($user);
if (!$ticket) return -1;
}
$parameter = array(ModelParameter::$ndg => $ndg);
$response = AlfrescoConnect::Query($url, $parameter,HTTP_METH_POST,1,1,AlfrescoConnect::$userTicket);
return $response;
}
}
It was a memory problem. Never ever try to run Alfresco on a machine with only 1GB of memory!

Repost: Creating a RSS feed with PHP

I asked how to do this before but it seems I needed to put more code to really get an answer.
I have a reddit type site, and I am trying to create a rss feed this is the code, but I get a Fatal error: Uncaught exception 'Exception' with message 'Query failed'
Here its the code:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
require_once(SITE_ROOT.'data/comment.php');
class Article extends Model
{
private $id;
private $user_id;
private $url;
private $title;
private $description;
private $ranking;
private $points;
function __construct($title = ' ', $description = ' ', $url = ' ', $username = ' ', $created = ' ', $modified = '') {
$this->setId(0);
$this->setCreated($created);
$this->setModified($modified);
$this->setUsername($username);
$this->setUrl($url);
$this->setTitle($title);
$this->setDescription($description);
$this->setRanking(0.0);
$this->setPoints(0);
}
function getId(){
return $this->id;
}
private function setId($value){
$this->id = $value;
}
function getUsername(){
return $this->username;
}
function setUsername($value){
$this->username = $value;
}
function getUrl(){
return $this->url;
}
function setUrl($value){
$this->url = $value;
}
function getTitle()
{
return $this->title;
}
function setTitle($value) {
$this->title = $value;
}
function getDescription() {
return $this->description;
}
function setDescription($value)
{
$this->description = $value;
}
function getPoints()
{
return $this->points;
}
function setPoints($value) {
$this->points = $value;
}
function getRanking()
{
return $this->ranking;
}
function setRanking($value)
{
$this->ranking = $value;
}
function calculateRanking()
{
$created = $this->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
$time = $diff['days'] * 24;
$time += $diff['hours'];
$time += ($diff['minutes'] / 60);
$time += (($diff['seconds'] / 60)/60);
$base = ($time + 2);
if($base > 0)
{
$this->ranking = ($this->points - 1) / pow($base, 1.5);
}
else
{
$this->ranking = 0;
}
$this->save();
}
function vote($user,$amount=1)
{
if($this->has_voted($user) == false)
{
$this->points += $amount;
$this->save();
$this->log_vote($user);
}
}
function log_vote($user)
{
try
{
$db = parent::getConnection();
$query = "insert into votes (article_id, username) values ($this->id, '$user')";
$results = parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
function has_voted($user)
{
try
{
$db = parent::getConnection();
$query = "select id from votes where username = '$user' and article_id = $this->id";
$results = parent::execSQL($query);
if($results->num_rows == 1) {
return true;
}
else
{
return false;
}
parent::closeConnection($db);
}
catch(Exception $e){
throw $e;
}
}
function getUrlDomain()
{
/* We extract the domain from the URL
* using the following regex pattern
*/
$url = $this->getUrl();
$matches = array();
if(preg_match('/http:\/\/(.+?)\//', $url, $matches))
{
return $matches[1];
}
else
{
return $url;
}
}
function getTimeDifference( $start, $end )
{
//echo "start is $start, end is $end";
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo( "Ending date/time is earlier than the start date/time");
}
}
else
{
echo( "Invalid date/time data detected");
}
return( false );
}
function getElapsedDateTime()
{
$db = null;
$record = null;
$record = Article::getById($this->id);
$created = $record->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
//$diff = $this->getTimeDifference($created, date_add(date('F d, Y h:i:s A'),new DateInterval("5H")));
//echo 'new date is '.date('F d, Y h:i:s A');
//print_r($diff);
if($diff['days'] > 0 )
{
if($diff['days'] < 2 ) { return sprintf("%d dia", $diff['days']); }
else return sprintf("%d dias", $diff['days']);
}
else if($diff['hours'] > 0 )
{
if($diff['hours'] < 2 ) { return sprintf("%d hora", $diff['hours']); }
else return sprintf("%d horas", $diff['hours']);
}
else if($diff['minutes'] > 0 )
{
if($diff['minutes'] < 2 ) { return sprintf("%d minuto", $diff['minutes']); }
else return sprintf("%d minutos", $diff['minutes']);
}
else
{
if($diff['seconds'] < 2 ) { return sprintf("%d segundo", $diff['seconds']); }
else return sprintf("%d segundos", $diff['seconds']);
}
}
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
createRSS(); // ++++++ rss +++++++
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
throw $e;
}
}
function delete()
{
try
{
$db = parent::getConnection();
if($this->id != 0)
{ ;
/*$comments = $this->getAllComments();
foreach($comments as $comment)
{
$comment->delete();
}*/
$this->deleteAllComments();
$query = "delete from articles where id = $this->id";
}
parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
static function getAll($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$db = null;
$results = null;
$records = array();
$query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
try
{
$db = parent::getConnection();
$results = parent::execSql($query);
while($row = $results->fetch_assoc())
{
$r_id = $row['id'];
$r_created = $row['created'];
$r_modified = $row['modified'];
$r_title = $row['title'];
$r_description = $row['description'];
if(!get_magic_quotes_gpc())
{
$r_title = stripslashes($r_title);
$r_description = stripslashes($r_description);
}
$r_url = $row['url'];
$r_username = $row['username'];
$r_points = $row['points'];
$r_ranking = $row['ranking'];
$article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
$article->id = $r_id;
$article->points = $r_points;
$article->ranking = $r_ranking;
$records[] = $article;
}
parent::closeConnection($db);
}
catch(Exception $e)
{
throw $e;
}
return $records;
}
static function getById($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select id, username, created, modified, title, url, description, points, ranking from articles where id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Record not found', EX_RECORD_NOT_FOUND);
}
$row = $results->fetch_assoc();
parent::closeConnection($db);
if(!get_magic_quotes_gpc())
{
$row['title'] = stripslashes($row['title']);
$row['description'] = stripslashes($row['description']);
}
$article = new Article($row['title'], $row['description'], $row['url'], $row['username'], $row['created'], $row['modified']);
$article->id = $row['id'];
$article->points = $row['points'];
$article->ranking = $row['ranking'];
return $article;
}
catch (Exception $e){
throw $e;
}
}
static function getNumberOfComments($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select count(*) as 'total' from comments where article_id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Comments Count Query Query Failed', EX_QUERY_FAILED);
}
$row = $results->fetch_assoc();
$total = $row['total'];
parent::closeConnection($db);
return $total;
}
catch (Exception $e){
throw $e;
}
}
function deleteAllComments()
{/*
* Return one record from the database by its id */
$db = null;
try
{
$db = parent::getConnection();
$query = "delete from comments where article_id = $this->id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Deletion Query Failed', EX_QUERY_FAILED);
}
parent::closeConnection($db);
}
catch (Exception $e){
throw $e;
}
}
function getAllComments($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$conditions = "where article_id = $this->id";
$comments = Comment::getAll($conditions);
return $comments;
}
static function getTestData($url)
{
$page = file_get_contents($url);
}
}
function createRSS()
{
$articles = Article::getAll("order by created desc limit $offset, $num_items");
$num_articles = count($articles);
// open a file pointer to an RSS file
$fp = fopen ("rss.xml", "w");
if (!$fp) {
// Can't write to a file
return;
}
fwrite ($fp, "<?xml version='1.0' encoding='iso-8859-1' ?>\n");
fwrite ($fp, "<rss version='2.0' xmlns:atom=\"http://www.kiubbo.com/rss.xml\"><channel>\n");
fwrite ($fp, "<title>Kiubbo.com</title>\n");
fwrite ($fp, "<atom:link href='http://www.kiubbo.com/rss.xml' rel='self' type='application/rss+xml' />\n");
fwrite ($fp, "<link>http://www.kiubbo.com/</link>\n");
fwrite ($fp, "<description>Todas las Noticias Fotos y Videos.</description>\n");
fwrite ($fp, "<language>es-mx</language>\n");
fwrite ($fp, "<docs>http://www.kiubbo.com/rss.xml</docs>\n");
fwrite ($fp, "<image>\n");
fwrite ($fp, " <title>Kiubbo.com</title>\n");
fwrite ($fp, " <url>http://www.kiubbo.com/Logot.png</url>\n");
fwrite ($fp, " <link>http://www.kiubbo.com</link>\n");
fwrite ($fp, "</image>\n");
for($index = 0; $index < $num_articles; $index++){
$url = $articles[$index]->getUrl();
$title = $articles[$index]->getTitle(); // ok?
$search = array(
'#<script[^>]*?>.*?</script>#si', // Strip out javascript
'#<[\/\!]*?[^<>]*?>#si', // Strip out HTML tags
'#([\r\n])[\s]+#', // Strip out white space
'#&(quot|#34);#i', // Replace HTML entities
'#&(amp|#38);#i',
'#&(lt|#60);#i',
'#&(gt|#62);#i',
'#&(nbsp|#160);#i',
'#&(iexcl|#161);#i',
'#&(cent|#162);#i',
'#&(pound|#163);#i',
'#&(copy|#169);#i',
'#&(acento|#0027);#i',
'#&#(\d+);#e'); // evaluate as php
$replace = array(
'',
'',
'\1',
'"',
'&',
'<',
'>',
' ',
'chr(161)',
'chr(162)',
'chr(163)',
'chr(169)',
'chr(\1)');
$content = preg_replace($search, $replace, $content);
$title = preg_replace("/&/", 'y', $title);
$content = preg_replace("/&/", 'y', $content);
fwrite ($fp, "<item>\n");
fwrite ($fp, " <title>$title</title>\n");
fwrite ($fp, " <link>$url</link>\n");
fwrite ($fp, "<guid>http://www.kiubbo.com</guid>\n");
fwrite ($fp, "</item>\n");
}
fwrite ($fp, "</channel></rss>\n");
fclose ($fp);
}
?>
Thx
Regards
Carlos
I'm not at a machine with php to test this, but you have queries with variables as follows...
"select id from votes where username = '$user' and article_id = $this->id"
I'm fairly certain that you need to bracket or concatenate when using objects...
"select id from votes where username = '$user' and article_id = ${this->id}"
or
"select id from votes where username = '$user' and article_id = " . $this->id

Categories