rawQuery() public méthode

Execute raw SQL query.
public rawQuery ( string $query, array $bindParams = null ) : array
$query string User-provided query to execute.
$bindParams array Variables array to bind to the SQL statement.
Résultat array Contains the returned rows from the query.
/**
 * @descr Obtiene las comentarios
 */
function getComentarios($post_id)
{
    $db = new MysqliDb();
    $results = $db->rawQuery('SELECT
    c.post_comentario_id,
    c.post_id,
    c.titulo,
    c.detalles,
    c.parent_id,
    c.creador_id,
    c.votos_up,
    c.votos_down,
    c.fecha,
    u.nombre,
    u.apellido
FROM
    posts_comentarios c
        LEFT JOIN
    usuarios u ON u.usuario_id = c.creador_id
WHERE
    c.post_id = ' . $post_id . '
    order by c.post_comentario_id;');
    echo json_encode($results);
}
Exemple #2
0
function getListComposersDb()
{
    $db = new MysqliDb(HOST, USER, PASSWORD, DBNAME);
    $query = "SELECT * FROM composers";
    $composers = $db->rawQuery($query);
    return $composers;
}
function order_paid()
{
    require_once './submodules/php-mysqli-database-class/MysqliDb.php';
    require './includes/config.php';
    $db = new MysqliDb($db_host, $db_user, $db_pass, $db_name);
    $payid = $_GET['out_trade_no'];
    $aPayId = explode('_', $payid);
    $mtrid = $aPayId[1];
    $params = json_encode($_GET);
    //验证是否已经支付过
    $db->where("mtr_id = '{$mtrid}'")->get('mark_trafficpolice_reward');
    if ($db->count == 0) {
        $aNew = array('mtr_id' => $mtrid, 'pay_id' => $payid, 'pay_success' => 1, 'pay_money' => $_GET['total_fee'], 'pay_date' => $_GET['gmt_payment'], 'pay_params' => $params, 'created_date' => $db->now());
        $id = $db->insert('mark_trafficpolice_reward', $aNew);
        //给用户增加余额
        $sql = "SELECT mt.user_id,u.user_money FROM `mark_trafficpolice` mt\n            LEFT JOIN mark_trafficpolice_received mtr ON mt.id=mtr.mt_id\n            LEFT JOIN users u ON u.user_id=mt.user_id\n            WHERE mtr.id= '{$mtrid}'";
        $aUser = $db->rawQuery($sql);
        if ($db->count) {
            $aUpdate = array('user_money' => $aUser[0]['user_money'] + $_GET['total_fee'], 'updated_date' => $db->now());
            $db->where('user_id', $aUser[0]['user_id']);
            $db->update('users', $aUpdate);
        }
    } else {
        echo "already rewarded";
    }
}
    $function = $_GET["function"];
    if ($function == 'get') {
        get();
    }
}
function get()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('select oferta_laboral_id, DATE_FORMAT(fecha,"%d-%m-%Y") fecha, titulo, detalle, cliente_id, status, 0 cliente from ofertas_laborales order by oferta_laboral_id desc');
    foreach ($results as $key => $row) {
        $db->where('cliente_id', $row["cliente_id"]);
Exemple #5
0
 function GET($matches)
 {
     if ($matches[1]) {
         $db = new MysqliDb($this->config["host"], $this->config["user"], $this->config["pass"], $this->config["base"]);
         $result = $db->where('idVIP', $matches[1])->get('VIP', 1);
         $realisateur = $db->where('realisateur', $matches[1])->get('film');
         $params = array($matches[1]);
         $acteur = $db->rawQuery("SELECT * FROM joue, film WHERE joue.idfilm = film.idfilm AND joue.idVIP = ?", $params);
         $photo = $db->rawQuery("SELECT * FROM vip_photo, photo WHERE photo.idphoto = vip_photo.idphoto AND vip_photo.idVIP = ?", $params);
         $data = array();
         $data["vip"] = $result[0];
         $data["acteur"] = $acteur;
         $data["realisateur"] = $realisateur;
         $data["photo"] = $photo;
         if (!empty($result) && count($result) > 0) {
             SimplestView::render("header");
             SimplestView::render('vip', $data);
             SimplestView::render("footer");
         }
     }
 }
Exemple #6
0
function insertCompositionsOnDB()
{
    $composers = getListComposers();
    foreach ($composers as $index => $composer) {
        $slug = getSlugComposer($composer);
        $relevance = $index + 1;
        $db = new MysqliDb(HOST, USER, PASSWORD, DBNAME);
        $query = "INSERT INTO `composers`(`slug`,`name`,`relevance`)";
        $query .= " VALUES ('" . $slug . "','" . $composer . "','" . $relevance . "');";
        echo $query . PHP_EOL;
        $db->rawQuery($query);
    }
}
Exemple #7
0
function insertComposersOnDB()
{
    $db = new MysqliDb(HOST, USER, PASSWORD, DBNAME);
    $composers = getListComposersDb();
    foreach ($composers as $index => $composer) {
        $compositions = extractCompositionsFromSearchHtmls($composer['name']);
        foreach ($compositions as $composition) {
            echo "Inserting " . $composition . "..." . PHP_EOL;
            $relevance = $index + 1;
            $query = "INSERT INTO `compositions`(`composer_id`,`name`,`relevance`)";
            $query .= " VALUES ('" . $composer['id'] . "','" . escapeSingleQuote($composition) . "','" . $relevance . "');";
            $db->rawQuery($query);
        }
    }
}
function getSlider($conProductos)
{
    $db = new MysqliDb();
    //    $results = $db->get('sliders');
    //    $results = $db->rawQuery('Select slider_id, o.producto_id producto_id, kit_id, precio, o.descripcion descripcion,
    //    imagen, titulo, p.nombre producto from sliders o inner join productos p on o.producto_id = p.producto_id;');
    $results = $db->rawQuery('Select oferta_id slider_id, o.producto_id producto_id, kit_id, precio, o.descripcion descripcion,
    imagen, titulo, 0 producto from ofertas o;');
    if ($conProductos) {
        foreach ($results as $key => $row) {
            $db->where('producto_id', $row["producto_id"]);
            $producto = $db->get('productos');
            $results[$key]["producto"] = $producto;
        }
    }
    echo json_encode($results);
}
Exemple #9
0
    $function = $_GET["function"];
    if ($function == 'get') {
        get();
    }
}
function get()
Exemple #10
0
<?php

require_once 'MysqliDb.php';
require_once 'config.php';
$db = new MysqliDb(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$table = $db->rawQuery("CREATE TABLE IF NOT EXISTS\n    `auction` (\n        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n        `auction_code` CHAR(50) NOT NULL,\n        `auction_page` CHAR(150) NOT NULL,\n        PRIMARY KEY(`id`)\n    )\nENGINE = InnoDB\nDEFAULT CHARACTER SET = utf8");
echo 'ok';
$table2 = $db->rawQuery("CREATE TABLE IF NOT EXISTS\n    `au_doc` (\n        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n        `auction_id` INT NOT NULL,\n        `au_doc_name` CHAR(250) NOT NULL,\n        `au_doc_link` CHAR(250) NOT NULL,\n        PRIMARY KEY(`id`)\n    )\nENGINE = InnoDB\nDEFAULT CHARACTER SET = utf8");
echo 'ok';
Exemple #11
0
foreach ($compositions as $numComposition => $composition) {
    // There were some problems when retrieving the data from YouTube
    // so, to avoid retrieving everything from scratch we set a start number
    if ($numComposition < $startComposition) {
        continue;
    }
    $maxResults = 25;
    $youtube = new Google_Service_YouTube($client);
    $searchResponse = $youtube->search->listSearch('id,snippet', array('q' => $composition['composition'] . " " . $composition['composer'], 'maxResults' => $maxResults, 'type' => 'video', 'order' => 'relevance', 'videoEmbeddable' => 'true'));
    foreach ($searchResponse as $index => $result) {
        $relevance = $index + 1;
        $videoId = $result->getId()->getVideoId();
        $videoTitle = $result->getSnippet()->getTitle();
        $videoDescription = $result->getSnippet()->getDescription();
        $query = "INSERT INTO `videos`(`composition_id`,`youtube_id`,`title`,`description`,`relevance` )";
        $query .= " VALUES ('" . $composition['id'] . "','" . $videoId . "','" . escapeSingleQuote($videoTitle) . "','" . escapeSingleQuote($videoDescription) . "','" . $relevance . "');";
        $db->rawQuery($query);
    }
    echo $numComposition + 1 . "/" . $countCompositions . ": Inserting videos for " . $composition['composition'] . PHP_EOL;
    usleep(150);
    // To avoid having problems with YouTube API quota limit
}
function test()
{
    $client = new Google_Client();
    $client->setApplicationName("Amadeus");
    $client->setDeveloperKey(YOUTUBE_API_KEY);
    $youtube = new Google_Service_YouTube($client);
    $searchResponse = $youtube->search->listSearch('id,snippet', array('q' => 'test', 'maxResults' => 25, 'type' => 'video', 'order' => 'relevance', 'videoEmbeddable' => 'true'));
    print_r($searchResponse);
}
        $id = $db->insert('history', $data);
        break;
    case 'getContractContent':
        $db = new MysqliDb();
        $db->where('id', $_GET['id']);
        $contracts = $db->getOne('contracts');
        echo json_encode($contracts);
        break;
    case 'getHistory':
        $db = new MysqliDb();
        $history = $db->rawQuery("SELECT * FROM history WHERE contract_id = ? AND doc_id = ? order by date desc", array($_POST['id'], $_POST['index']));
        echo json_encode($history);
        break;
    case 'getHistoryId':
        $db = new MysqliDb();
        $history = $db->rawQuery("SELECT id,create_date FROM vwhistory WHERE contract_id = ? AND doc_id = ? order by id desc", array($_POST['id'], $_POST['index']));
        echo json_encode($history);
        break;
    case 'saveStatus':
        $db = new MysqliDb();
        $db->where('id', $_GET['id']);
        $data = array('initialed' => implode(",", $_POST['status']));
        $templates = $db->update('contracts', $data);
        echo json_encode($data);
        break;
    default:
        # code...
        break;
}
function printToServer($content, $name, $client, $folder_name, $version)
{
/**
 * @descr Obtiene las categorias
 */
function getCategorias()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('SELECT c.*, (select count(producto_id) from productos_categorias p where p.categoria_id= c.categoria_id) total, d.nombre nombrePadre FROM categorias c LEFT JOIN categorias d ON c.parent_id = d.categoria_id;');
    echo json_encode($results);
}
function getNoticias()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('Select noticia_id, titulo, detalles, fecha, creador_id, vistas, tipo, 0 fotos, 0 comentarios from noticias;');
    foreach ($results as $key => $row) {
        $db->where('noticia_id', $row["noticia_id"]);
        $fotos = $db->get('noticias_fotos');
        $results[$key]["fotos"] = $fotos;
        $db->where('noticia_id', $row["noticia_id"]);
        $comentarios = $db->get('noticias_comentarios');
        $results[$key]["comentarios"] = $comentarios;
    }
    echo json_encode($results);
}
Exemple #15
0
<?php

require_once 'MysqliDb.php';
require_once 'config.php';
$db = new MysqliDb(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$users = $db->rawQuery("CREATE TABLE\n    `users` (\n        `login` CHAR(50) NOT NULL,\n        `password` CHAR(150) NOT NULL,\n        `name` CHAR(30) NOT NULL,\n        `email` CHAR(50) NOT NULL,\n        PRIMARY KEY(`login`)\n    )");
echo 'ok';
Exemple #16
0
    $subject = stripslashes(trim($_POST['subject']));
    $message = stripslashes(trim($_POST['message']));
    $phone = stripslashes(trim($_POST['phone']));
    //$name = 'sadf';
    //$email = '*****@*****.**';
    //$subject = 'sadf';
    //$/message = 'dsf';
    if (empty($name)) {
        $errors['name'] = 'Name is required.';
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Email is invalid.';
    }
    if (empty($subject)) {
        $errors['subject'] = 'Subject is required.';
    }
    if (empty($message)) {
        $errors['message'] = 'Message is required.';
    }
    // if there are any errors in our errors array, return a success boolean or false
    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors'] = $errors;
    } else {
        $data['success'] = true;
        $data['message'] = 'Congratulations. Your message has been sent successfully';
        $db->rawQuery("INSERT INTO `twistitlabs`.`contacts` (`name`,`email`,`subject`,`message`, `phone`) VALUES ('{$name}','{$email}','{$subject}','{$message}', '{$phone}')");
    }
    // return all our data to an AJAX call
    echo json_encode($data);
}
Exemple #17
0
<?php

// Создание таблицы для каталога
require_once 'MysqliDb.php';
require_once 'config.php';
$db = new MysqliDb(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$users = $db->rawQuery("CREATE TABLE\n    `books` (\n    \t`id` INT(8) NOT NULL AUTO_INCREMENT,\n        `name` CHAR(255) NOT NULL,\n        `genre` CHAR(150) NOT NULL,\n        `author` CHAR(255) NOT NULL,\n        `year` INT(4) NOT NULL,\n        PRIMARY KEY(`id`)\n    )\nCOLLATE utf8_general_ci");
echo 'Таблица для каталога создана<br>';
$data = array("name" => "Турецкий гамбит", "genre" => "детектив", "author" => "Акунин Б.", "year" => "2002");
$id = $db->insert('books', $data);
if ($id) {
    echo 'book\'s sign was created. Id=' . $id . '<br>';
}
$data = array("name" => "Дюна", "genre" => "фантастика", "author" => "Герберт Ф.", "year" => "1965");
$id = $db->insert('books', $data);
if ($id) {
    echo 'book\'s sign was created. Id=' . $id . '<br>';
}
$data = array("name" => "Гамлет", "genre" => "драма", "author" => "Шекспир В.", "year" => "1601");
$id = $db->insert('books', $data);
if ($id) {
    echo 'book\'s sign was created. Id=' . $id . '<br>';
}
$data = array("name" => "Война и мир", "genre" => "драма", "author" => "Толстой Л.", "year" => "1869");
$id = $db->insert('books', $data);
if ($id) {
    echo 'book\'s sign was created. Id=' . $id . '<br>';
}
$data = array("name" => "Мертвые души", "genre" => "драма", "author" => "Гоголь Н.", "year" => "1847");
$id = $db->insert('books', $data);
if ($id) {
function getNoticias()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('Select noticia_id, titulo, subtitulo, link, detalles, fecha, creador_id, vistas, tipo, 0 fotos, 0 comentarios from noticias order by noticia_id desc;');
    foreach ($results as $key => $row) {
        $db->where('noticia_id', $row["noticia_id"]);
        $fotos = $db->get('noticias_fotos');
        $results[$key]["fotos"] = $fotos;
        $sql_comment = 'SELECT noticia_comentario_id, noticia_id,titulo,detalles,parent_id,creador_id,0 creador,votos_up,votos_down,fecha FROM noticias_comentarios WHERE noticia_id = ' . $row["noticia_id"] . ';';
        $comentarios = $db->rawQuery($sql_comment);
        foreach ($comentarios as $keyComment => $rowComment) {
            $db2 = new MysqliDb();
            $db2->where('cliente_id', $rowComment['creador_id']);
            $cliente = $db2->get('clientes');
            $comentarios[$keyComment]['creador'] = $cliente;
        }
        $results[$key]["comentarios"] = $comentarios;
    }
    echo json_encode($results);
}
														CREATE CSV
********************************************************************************************************************************
*******************************************************************************************************************************/
$log->debug('Creating CSV');
//FULL CSV Path
$CVSFilePath = $CSVFileLocation . $CSVfileName;
//Delete old file CSV file
$log->debug('Deleting old CSV File');
if (!unlink($CVSFilePath)) {
    $log->error('Could not delete old CSV');
}
//Prepare the SQL
$SQL = "SELECT 'date_submitted', 'identifier', 'firstName','lastName','nickName','mobilePhone','primaryEmail','custom1','custom2','custom3','importPhotoPath'\n\t\tUNION ALL\n\t\tSELECT `date_submitted`,`identifier`,`First Name`,`Last Name`,IFNULL(Nickname,''),`Phone Number`,`Email`,`Text Ok`,`Grade`,`Birthday`,`Dropbox Image Path` \n\t\tFROM student_list\n\t\tWHERE `Grade`!='Graduated';";
$log->debug('Running getting Uers and running SQL');
//Excute it
$resultRaw = $db->rawQuery($SQL);
if (!$resultRaw) {
    $log->error('SQL query failed');
    $log->error('Invalid query: ' . mysql_error());
    failed();
    exit;
}
$log->info('Creating CVS File on Disk');
//Create the file on Disk
if (!($handle = fopen($CVSFilePath, 'w'))) {
    $log->error('Could not create CSV file on Disk');
    failed();
    exit;
}
$log->debug('Writing data to CSV file');
foreach ($resultRaw as $row) {
Exemple #20
0
    public function filterByTerm($query, $offset, $count, $format, $override = "no")
    {
        if ($override != "yes") {
            $published = "AND published = 'true'";
        } else {
            $published = "";
        }
        $db = new MysqliDb(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        $term = "%" . $query . "%";
        $result = $db->rawQuery('SELECT * 
										FROM trails 
										WHERE name LIKE ? ' . $published . '
										LIMIT ? , ?;', array($term, $offset, $count));
        $trails = array();
        foreach ($result as $id => $trail) {
            $trails[$trail['id']] = $trail;
            $attractions = json_decode(stripslashes($trail['attractions']));
            $trails[$trail['id']]['attractions'] = $attractions;
            $loops = json_decode(stripslashes($trail['loops']));
            $trails[$trail['id']]['loops'] = array();
            foreach ($loops as $id => $data) {
                $trails[$trail['id']]['loops'][$id] = (array) $data;
            }
            $trails[$trail['id']]['satImgURL'] = BASE_URL . $trail['satImgURL'];
            $trails[$trail['id']]['largeImgURL'] = BASE_URL . $trail['largeImgURL'];
            $trails[$trail['id']]['thumbURL'] = BASE_URL . $trail['thumbURL'];
            $trails[$trail['id']]['url'] = BASE_URL . "trail/" . $trail['id'] . "/" . $this->slugify($trail['name']) . "/";
        }
        $total = count($trails);
        $trails = array_slice($trails, $offset, $count);
        $response['trails'] = $trails;
        $response['countReturned'] = count($trails);
        $response['totalMatched'] = $total;
        if ($format == "JSON") {
            return json_encode($response);
        } elseif ($format == "XML") {
            return "Maybe someday..";
        } else {
            return $response;
        }
    }
Exemple #21
0
        $player_names[] = $_REQUEST[$tmp];
    }
}
$done = false;
if (isset($_REQUEST["done"]) && !empty($_REQUEST["done"])) {
    $done = true;
}
$db = new MysqliDb('localhost', 'root', '', 'golf-cards');
$time = time();
$name = $time . "names";
$scores = $time . "scores";
$q = "CREATE TABLE {$name} (id INT(9) UNSIGNED PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30) NOT NULL)";
$w = "CREATE TABLE {$scores} (id INT(9) UNSIGNED PRIMARY KEY AUTO_INCREMENT, player_id int(30) NOT NULL, round int(30) NOT NULL, score int(30) NOT NULL)";
if ($done) {
    //!empty($num_players) && count($player_names) == $num_players
    $tmp = $db->rawQuery($q);
    $tmp = $db->rawQuery($w);
    $data = array("game_id" => $time, "friendly_name" => $game_name);
    $id = $db->insert("game_names", $data);
    for ($i = 0; $i < $num_players; $i++) {
        $data = array("name" => $player_names[$i]);
        $id = $db->insert($name, $data);
    }
    for ($i = 0; $i < $num_players; $i++) {
        $data = array("player_id" => strval($i + 1), "round" => 0, "score" => 0);
        $id = $db->insert($scores, $data);
    }
    $int = 43200;
    setcookie("game", $time, time() + $int);
    setcookie("mod", "true", time() + $int);
    $host = $_SERVER['HTTP_HOST'];
/**
 * @description Mueve una determinada cantidad de un producto a otra sucursal
 * @param $origen_id
 * @param $destino_id
 * @param $producto_id
 * @param $cantidad
 */
function trasladar($origen_id, $destino_id, $producto_id, $cantidad)
{
    $db = new MysqliDb();
    $cant_a_mover = $cantidad;
    $stock_origen = $db->rawQuery('select stock_id, cant_actual, costo_uni, proveedor_id from stock where sucursal_id = ' . $origen_id . '
and producto_id = ' . $producto_id . ' order by stock_id asc');
    foreach ($stock_origen as $row) {
        if ($cant_a_mover > 0 && $row["cant_actual"] > 0) {
            if ($row["cant_actual"] < $cant_a_mover) {
                $db->where('stock_id', $row['stock_id']);
                $data = array('cant_actual' => 0);
                $db->update('stock', $data);
                $insertar = array('producto_id' => $producto_id, 'proveedor_id' => $row['proveedor_id'], 'sucursal_id' => $destino_id, 'cant_actual' => $cant_a_mover - $row["cant_actual"], 'cant_inicial' => $cant_a_mover - $row["cant_inicial"], 'costo_uni' => $row['costo_uni']);
                $db->insert('stock', $insertar);
                $cant_a_mover = $cant_a_mover - $row["cant_actual"];
            }
            if ($row["cant_actual"] > $cant_a_mover) {
                $db->where('stock_id', $row['stock_id']);
                $data = array('cant_actual' => $row["cant_actual"] - $cant_a_mover);
                $db->update('stock', $data);
                $insertar = array('producto_id' => $producto_id, 'proveedor_id' => $row['proveedor_id'], 'sucursal_id' => $destino_id, 'cant_actual' => $cant_a_mover, 'cant_inicial' => $cant_a_mover, 'costo_uni' => $row['costo_uni']);
                $db->insert('stock', $insertar);
                $cant_a_mover = 0;
            }
            if ($row["cant_actual"] == $cant_a_mover) {
                $db->where('stock_id', $row['stock_id']);
                $data = array('cant_actual' => 0);
                $db->update('stock', $data);
                $insertar = array('producto_id' => $producto_id, 'proveedor_id' => $row['proveedor_id'], 'sucursal_id' => $destino_id, 'cant_actual' => $cant_a_mover, 'cant_inicial' => $cant_a_mover, 'costo_uni' => $row['costo_uni']);
                $db->insert('stock', $insertar);
                $cant_a_mover = 0;
            }
        }
    }
    echo json_encode($db->getLastError());
}
function checkLastLogin($userid)
{
    $db = new MysqliDb();
    $results = $db->rawQuery('select TIME_TO_SEC(TIMEDIFF(now(), last_login)) diferencia from usuarios where usuario_id = ' . $userid);
    if ($db->count < 1) {
        $db->rawQuery('update usuarios set token ="" where usuario_id =' . $userid);
        echo json_encode(-1);
    } else {
        $diff = $results[0]["diferencia"];
        if (intval($diff) < 12960) {
            echo json_encode($results[0]);
        } else {
            $db->rawQuery('update usuarios set token ="" where usuario_id =' . $userid);
            echo json_encode(-1);
        }
    }
}
         } catch (\Zelenin\Telegram\Bot\NotOkException $e) {
             echo $e->getMessage();
         }
     } else {
         try {
             $response = $client->forwardMessage(['chat_id' => $agroup, 'message_id' => $messageid, 'from_chat_id' => $chatid]);
         } catch (\Zelenin\Telegram\Bot\NotOkException $e) {
             echo $e->getMessage();
         }
     }
     break;
 case '/count':
 case '/count@jadibot':
 case '/count@JadiBot':
     if ($chatid == $agroup) {
         $users = $db->rawQuery('SELECT count(distinct Fid) as count from jadi_recived');
         $users = $users[0];
         $users = $users['count'];
         $allmsg = $db->rawQuery('SELECT count(*) as count from jadi_recived');
         $allmsg = $allmsg[0];
         $allmsg = $allmsg['count'];
         try {
             $params = ['chat_id' => $chatid, 'action' => 'typing'];
             $response = $client->sendChatAction($params);
             $defaulttext = "درحال حاضر 👤" . $users . " کاربر از روبات ما استفاده میکنند.\n و این روبات تاکنون 📩" . $allmsg . " پیام را دریافت کرده است.";
             $params = ['chat_id' => $chatid, 'text' => $defaulttext, 'reply_to_message_id' => $messageid];
             $response = $client->sendMessage($params);
         } catch (\Zelenin\Telegram\Bot\NotOkException $e) {
             echo $e->getMessage();
         }
     } else {
<?php

require_once 'includes/MyDBi.php';
require 'ac-angular-contacts/includes/PHPMailerAutoload.php';
$db = new MysqliDb();
$results = $db->rawQuery('select p.proyecto_id proyecto_id, p.nombre, u.nombre nombreUsuario, u.mail
from proyectos p left join usuarios u on p.usuario_id = u.usuario_id
where fecha_fin < now() and status =1;', '', false);
foreach ($results as $row) {
    $data = array('status' => 2);
    $db->where('proyecto_id', $row['proyecto_id']);
    $db->update('proyectos', $data);
    sendMail('*****@*****.**', $row['mail'], 'MPE', 'Su proyecto ' . $row['nombre'] . ' ha finalizado', $row['nombreUsuario'] . ' te informamos que tu proyecto ' . $row['nombre'] . ' ha finalizado');
}
function sendMail($mail_origen, $mails_destino, $nombre, $mensaje, $asunto)
{
    $mail = new PHPMailer();
    $mail->isSMTP();
    // Set mailer to use SMTP
    $mail->Host = 'gator4184.hostgator.com';
    // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;
    // Enable SMTP authentication
    $mail->Username = '******';
    // SMTP username
    $mail->Password = '******';
    // SMTP password
    $mail->SMTPSecure = 'ssl';
    // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;
    $mail->CharSet = 'UTF-8';
<?php

require_once '/API/MysqliDb.php';
$db = new MysqliDb('localhost', 'root', '', 'dnd');
$db->rawQuery("\n\tCREATE TABLE IF NOT EXISTS Users \n\t(\n\t\tid INT NOT NULL AUTO_INCREMENT,\t\t\t\t\t\t\t# user id\n\t\tpasswod VARCHAR(60) NOT NULL,\t\t\t\t\t\t\t# user password\n\t\tadmin INT(1) NOT NULL DEFAULT 0,\t\t\t\t\t\t# rights(ie. admin, user, etc....)\n\t\tactive BOOLEAN,\t\t\t\t\t\t\t\t\t\t\t# activly logged in\n\t\tfName VARCHAR(255) CHARACTER SET utf8 NOT NULL,\t\t\t# first name\n\t\tlName VARCHAR(255) CHARACTER SET utf8 NOT NULL,\t\t\t# last name  \n\t\tphone VARCHAR(16),\t\t\t\t\t\t\t\t\t\t# phone number\n\t\temail VARCHAR(128) CHARACTER SET utf8 NOT NULL UNIQUE,\t# email address\n\t\tintro VARCHAR(1024) CHARACTER SET utf8,\t\t\t\t\t# self-introduction\n\t\tpicture VARCHAR(256),\t\t\t\t\t\t\t\t\t# picture path\n\t\tcreatedAt DATETIME,\t\t\t\t\t\t\t\t\t\t# creation datetime\n\t\texpires DATETIME,\t\t\t\t\t\t\t\t\t\t# expiry datetime\n\t\tPRIMARY KEY (id),\n\t\tCONSTRAINT fullName UNIQUE (fName, lName)\n\t) ENGINE=InnoDB;\n\t");
$db->rawQuery("\n\tCREATE TABLE IF NOT EXISTS Posts \n\t(\n\t\tid INT NOT NULL AUTO_INCREMENT,\t\t\t\t\t\t\t# user id\n\t\tuID INT NOT NULL,\n\t\tmessage TEXT NOT NULL,\t\t\t\t\t\t\t\t\t# picture path\n\t\tpostedAt DATETIME,\t\t\t\t\t\t\t\t\t\t# creation datetime\n\t\teditedAt DATETIME,\t\t\t\t\t\t\t\t\t\t# expiry datetime\n\t\tPRIMARY KEY (id),\n\t\tFOREIGN KEY (uID) REFERENCES Users(id) \n\t) ENGINE=InnoDB;\n\t");
$db->rawQuery("\n\tCREATE TABLE IF NOT EXISTS CharTypes \n\t(\n\t\tcharID INT NOT NULL AUTO_INCREMENT,\t\t\t\t\t\t# character id\n\t\tcharType VARCHAR(255) NOT NULL,\t\t\t\t\t\t\t\t# character sheet type\n\t\tPRIMARY KEY (charID, charType) \n\t) ENGINE=InnoDB;\n\t");
$db->rawQuery("\n\tCREATE TABLE IF NOT EXISTS UserChars\n\t(\n\t\tchariD INT NOT NULL,\t\t\t\t\t\t\t\t\t# character id\n\t\tuID INT NOT NULL,\t\t\t\t\t\t\t\t\t\t# user id\n\t\tPRIMARY KEY (charID, uID),\n\t\tFOREIGN KEY (charID) REFERENCES CharTypes(charID),\n\t\tFOREIGN KEY (uID) REFERENCES Users(id) \n\t) ENGINE=InnoDB;\n\t");
/**
 * @description Retorna las donaciones, en caso de ser la consulta de un usuario, solo trae las del usuario
 * @param $usuario_id
 */
function getDonaciones($usuario_id)
{
    $db = new MysqliDb();
    $where = '';
    if ($usuario_id != -1) {
        $where = 'c.donador_id in (select usuario_id from proyectos p1 where p1.proyecto_id = p.proyecto_id)';
    }
    $results = $db->rawQuery('donaciones c', null, 'c.donacion_id, c.status, c.total, c.fecha, c.usuario_id, u.nombre, u.apellido');
    foreach ($results as $key => $row) {
        $db = new MysqliDb();
        $db->where('donacion_id', $row['donacion_id']);
        $db->join("proyectos p", "p.proyecto_id=c.proyecto_id", "LEFT");
        $proyectos = $db->get('donacion_detalles c', null, 'c.donacion_detalle_id, c.donacion_id, c.proyecto_id, p.nombre, c.cantidad, c.en_oferta, c.precio_unitario');
        $results[$key]['proyectos'] = $proyectos;
    }
    echo json_encode($results);
}
Exemple #28
-1
function getHistoricoPedidos($cliente_id)
{
    $db = new MysqliDb();
    $pedidos = array();
    $SQL = "SELECT carritos.carrito_id,\n            carritos.status,\n            carritos.total,\n            date(carritos.fecha) as fecha,\n            carritos.cliente_id,\n            0 detalles\n            FROM carritos\n            WHERE cliente_id = " . $cliente_id . " ORDER BY carritos.carrito_id DESC;";
    $results = $db->rawQuery($SQL);
    foreach ($results as $row) {
        $SQL = 'SELECT
                carrito_detalle_id,
                p.producto_id,
                cantidad,
                precio,
                p.nombre
                FROM carrito_detalles cd
                INNER JOIN productos p
                ON cd.producto_id = p.producto_id
                WHERE carrito_id = ' . $row['carrito_id'] . ';';
        $detalle = $db->rawQuery($SQL);
        $row['detalles'] = $detalle;
        array_push($pedidos, $row);
    }
    echo json_encode($pedidos);
}