public function saveMessage($msg)
   {
       $data = json_decode($msg);
       $conversationId = $data->id;
       $userId = $data->userId;
       $content = $data->content;
       $db = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
       $stmt = $db->prepare('
	INSERT INTO messages
	(
	conversationId,
	userId,
	content,
	date
	)
	VALUES
	(
	?,
	?,
	?,
	?
	)
	');
       if ($stmt) {
           $stmt->bind_param('iiss', $conversationId, $userId, $content, date('Y-m-d H:i:s'));
           $stmt->execute();
           $stmt->close();
           $db->close();
           return true;
       } else {
           return false;
       }
   }
Example #2
1
function sendNotifEmail($toId, $from, $type, $id)
{
    $username = "uv023890";
    $password = "porotos1";
    $hostname = "localhost";
    $db = "comm";
    $db = new mysqli($hostname, $username, $password, $db);
    $db->set_charset("utf8");
    $to = $db->query("SELECT user FROM tblusers WHERE userId='" . $toId . "'")->fetch_array();
    switch ($type) {
        case 0:
            //Photo
            $link = "http://comunidad.nitragin.com.ar/album.php?id=" . $id;
            $text = "album de fotos";
            break;
        case 1:
            //File
            $link = "http://comunidad.nitragin.com.ar/file.php?id=" . $id;
            $text = "archivo";
            break;
        case 2:
            //Message
            $link = "http://comunidad.nitragin.com.ar/msg.php?id=" . $id;
            $text = "mensaje";
            break;
    }
    $email = '<!DOCTYPE html ><html><body><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><center><table id="wrapper" width="600" cellspacing="0" cellpadding="0" border="0" ><tr><td style="padding:0px;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif;text-align: center"><img style="border:0;height:auto;line-height:100%;outline:none;text-decoration:none;float:left;" width="600" height="67" src="http://comunidad.nitragin.com.ar/mailing/notif/img/header.png"/></a></td></tr><tr><td style="border-collapse:collapse;padding-right:31px;font-family:Helvetica, sans-serif;padding-top:25px;"><table style="margin:0;"><tr><td style="padding:0;padding-left:150px;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif;text-align: center;padding-top:20px;" ><img width="44" height="44" src="http://comunidad.nitragin.com.ar/mailing/notif/img/msg.png"/ style="float:right;border:0;height:auto;line-height:100%;outline:none;text-decoration:none;"><br></td><td style="padding:0;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif;text-align: center;padding-top:10px;"><p style="font-family:Helvetica, sans-serif;float:left;font-size:15px;color:#66686A;margin:0;mso-line-height-rule:exactly;line-height:13px;text-align: left;">Has recibido un nuevo mensaje de<br>' . $from . '</p></td></tr></table></td></tr><tr><td style="border-collapse:collapse;font-family:Helvetica, sans-serif;text-align:center;padding-bottom:40px;"><table style="margin:0;"><tr><td style="padding:0;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif;text-align: center;padding-left:240px;" ><a href="' . $link . '"><img src="http://comunidad.nitragin.com.ar/mailing/notif/img/more.png" width="53" height="20"></a></td></tr></table></td></tr><tr><td style="border-collapse:collapse;font-family:Helvetica, sans-serif;text-align:center;background-color:#3F2B3C"><table style="margin:0;"><tr><td style="padding:7px 0px;padding-left:20px;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif;text-align: left;" ><img width="139" height="20" src="http://comunidad.nitragin.com.ar/mailing/notif/img/commL.png"/ style="float:right;border:0;height:auto;line-height:100%;outline:none;text-decoration:none;"><br></td></tr></table></td></tr></table></center><style type="text/css">table{font-family:Arial, Helvetica, sans-serif;border:0;}p{text-align:justify;}</style><style type="text/css">/* Client-specific Styles */#outlook a{padding:0;}/* Force Outlook to provide a "view in browser" button. */body{width:100% !important;}.ReadMsgBody{width:100%;}.ExternalClass{width:100%;}/* Force Hotmail to display emails at full width */body{-webkit-text-size-adjust:none;}/* Prevent Webkit platforms from changing default text sizes. *//* Reset Styles */body{margin:0px auto;padding:0;font-family:Arial, Helvetica, sans-serif;}img{border:0;height:auto;line-height:100%;outline:none;text-decoration:none;float:left;}</style></body></html>';
    $subject = "Nueva notificacion en Nitragin Comunidad";
    $fromM = "community@nitragin.com.ar";
    $headers = "From:" . $fromM . "\r\n";
    $headers .= "Reply-To:soporte@nitragin.com.ar\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    mail($to['user'], $subject, $email, $headers);
}
 /**
  * (non-PHPdoc)
  * @see IUserLoginMethod::authenticateWithEmail()
  */
 public function authenticateWithEmail($email, $password)
 {
     // connect to a data base
     // Note: If your source application shares the same data base, you can simply use $this->_db, rather than open another connection.
     $mysqli = new mysqli($this->_websoccer->getConfig('db_host'), $this->_websoccer->getConfig('db_user'), $this->_websoccer->getConfig('db_passwort'), $this->_websoccer->getConfig('db_name'));
     // get user from your source table
     $escapedEMail = $mysqli->real_escape_string($email);
     $dbresult = $mysqli->query('SELECT password FROM mydummy_table WHERE email = \'' . $escapedEMail . '\'');
     if (!$dbresult) {
         throw new Exception('Database Query Error: ' . $mysqli->error);
     }
     $myUser = $dbresult->fetch_array();
     $dbresult->free();
     $mysqli->close();
     // could not find user
     if (!$myUser) {
         return FALSE;
     }
     // check is password is correct (in this sample case a simple MD5 hashing is applied).
     if ($myUser['password'] != md5($password)) {
         return FALSE;
     }
     // user is valid user according to custom authentication check. Now test if user already exists in local DB and return its ID.
     $existingUserId = UsersDataService::getUserIdByEmail($this->_websoccer, $this->_db, strtolower($email));
     if ($existingUserId > 0) {
         return $existingUserId;
     }
     // if user does not exist, create a new one. Nick name can be entered by user later.
     return UsersDataService::createLocalUser($this->_websoccer, $this->_db, null, $email);
 }
Example #4
1
function handle_login()
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    require_once 'db.conf';
    $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($mysqli->connect_error) {
        $error = 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
        require "login_form.php";
        exit;
    }
    $username = $mysqli->real_escape_string($username);
    $password = $mysqli->real_escape_string($password);
    $query = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}'";
    $mysqliResult = $mysqli->query($query);
    // print_r(mysqli_fetch_all($mysqliResult,MYSQLI_ASSOC));
    if ($mysqliResult) {
        $match = $mysqliResult->num_rows;
        $mysqliResult->close();
        $mysqli->close();
        //print "The match is $match";
        if ($match == 1) {
            $_SESSION['loggedin'] = $username;
            header("Location: home.php");
            exit;
        } else {
            $error = "Incorrect username or password";
            require "login_form.php";
            exit;
        }
    }
}
Example #5
1
function getMailData()
{
    $mysqli = new mysqli($GLOBALS["servername"], $GLOBALS["server_username"], $GLOBALS["server_password"], $GLOBALS["database"]);
    $stmt = $mysqli->prepare("SELECT comment_id, user_id, text FROM eksam_comment WHERE send_email = ?");
    $stmt->bind_param("s", $_SESSION["user_email"]);
    $stmt->bind_result($comment_id, $id_mail, $text);
    $stmt->execute();
    // tühi massiiv kus hoiame objekte (1 rida andmeid)
    $array = array();
    // tee tsüklit nii mitu korda, kui saad
    // ab'ist ühe rea andmeid
    while ($stmt->fetch()) {
        // loon objekti iga while tsükli kord
        $mail = new StdClass();
        $mail->comment_id = $comment_id;
        $mail->id_mail = $id_mail;
        $mail->text = $text;
        // lisame selle massiivi
        array_push($array, $mail);
        //echo "<pre>";
        //var_dump($array);
        //echo "</pre>";
    }
    $stmt->close();
    $mysqli->close();
    return $array;
}
Example #6
1
 public function createCSV($selectedName)
 {
     // output headers so that the file is downloaded rather than displayed
     header('Content-Type: text/csv; charset=utf-8');
     header('Content-Disposition: attachment; filename=HRdata.csv');
     // create a file pointer connected to the output stream
     $file = fopen('php://output', 'w');
     // Connect to the DB
     $servername = "localhost";
     $username = "root";
     $password = "";
     $dbname = "rfid_database";
     $conn = new mysqli($servername, $username, $password, $dbname);
     // Fetch the data
     $sql = "SELECT users.userName, nomenclature.nomenclature_Name, locations.roomNumber, makes.makeName, models.model_Name, items.rfid, items.serialNum FROM items join locations on items.location_id=locations.location_id join models on items.model_id=models.model_id join nomenclature on nomenclature.nomenclature_id=models.nom_id join makes on models.make_id=makes.make_id join users on users.user_id=items.hrholder_id WHERE userName like '%{$selectedName}%'";
     $result = $conn->query($sql);
     // Headers for the file
     fputcsv($file, array('Nomenclature', 'Count', 'Location', 'Make', 'Model', 'Serial Number', 'RFID'));
     // Place the data in the file
     if ($result->num_rows > 0) {
         // output data of each row
         while ($row = $result->fetch_assoc()) {
             fputcsv($file, array($row["nomenclature_Name"], "Count Holder", $row["roomNumber"], $row["makeName"], $row["model_Name"], $row["rfid"], $row["serialNum"]));
         }
     }
     fclose($file);
 }
Example #7
1
function create_user($email, $passwd, $repasswd, $firstname, $middlename, $lastname)
{
    if (strcmp($passwd, $repasswd) !== 0) {
        die("Password and Re-Enter Password is not equal");
    }
    $sql = "INSERT INTO user001 (ur_id, password, f_nm, m_nm, l_nm, cr_dt, cr_by)\nVALUES ('{$email}', '{$passwd}', '{$firstname}', '{$middlename}', '{$lastname}', now(), current_user());";
    $h_success = "Location:reg_success.html";
    $h_fail = "Location:reg_fail.php";
    $servername = "localhost";
    $username = "root";
    $password = "College@2015";
    $dbname = "ESPDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    if ($conn->query($sql) === TRUE) {
        echo "User Successfully Registered";
        register($_POST[firstname], $_POST[middlename], $_POST[lastname], $_POST[email], $_POST[dob], $_POST[phone], $_POST[addr1], $_POST[addr2], $_POST[city], $_POST[state], $_POST[country], $_POST[postalCode]);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        $msg = "Error: " . "<br>" . $conn->error;
        $h_fail = $h_fail . "?msg=" . $msg;
        header($h_fail);
        exit;
    }
    $conn->close();
}
Example #8
1
function writeLog($Redirected_URL)
{
    //	Add logging to MySQL database
    $mySQL_username = "";
    $mySQL_password = "";
    $mySQL_database = "";
    //	Connect to database
    $mysqli = new mysqli('localhost', $mySQL_username, $mySQL_password, $mySQL_database);
    /* check connection */
    if (!mysqli_connect_errno()) {
        /* create a prepared statement */
        if ($stmt = $mysqli->prepare("INSERT INTO `stats`\t(`Datetime`,\t`UA`,\t`IP`,\t`Languages`,\t`Domain`,\t`Path`,\t`Destination`) \n\t\t\t\t\t\t\t\t\tVALUES \t(?,\t\t\t\t?,\t\t?,\t\t?,\t\t\t\t \t?,\t\t\t\t?,\t\t\t?)")) {
            $stmt->bind_param('sssssss', $datetime, $ua, $ip, $languages, $domain, $path, $destination);
            $datetime = date("Y-m-d H:i:s");
            $ua = $_SERVER['HTTP_USER_AGENT'];
            $ip = $_SERVER["REMOTE_ADDR"];
            $languages = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
            $domain = $_SERVER['SERVER_NAME'];
            $path = stripslashes($_GET['title']);
            $destination = $Redirected_URL;
            /* execute prepared statement */
            $stmt->execute();
            /* close statement and connection */
            $stmt->close();
            // Write a log file entry for each visitor
            $myFile = "log.txt";
            $fh = fopen($myFile, 'a+');
            // Tab separated. Date/Time	User Agent	IP Address	Language	Server requested	Page requested
            $stringData = $datetime . "\t" . $ua . "\t" . $ip . "\t" . $languages . "\t" . $domain . "\t" . $path . "\t" . $destination . "\n";
            fwrite($fh, $stringData);
            fclose($fh);
        }
    }
}
Example #9
1
 public function testLogin1()
 {
     $servername = "172.16.4.106";
     $username = "stdev";
     $password = "stdev";
     $dbname = "myDB";
     // Create connection
     $conn = new mysqli($servername, $username, $password, $dbname);
     // Check connection
     if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
     }
     $sql = "SELECT id, firstname, lastname FROM MyGuests";
     $result = $conn->query($sql);
     if ($result->num_rows > 0) {
         // output data of each row
         while ($row = $result->fetch_assoc()) {
             echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
         }
     } else {
         echo "0 results";
     }
     $conn->close();
     exit;
 }
Example #10
0
function UpdatePWD($id, $new_pwd)
{
    global $MYSQL_DB_NAME;
    global $MYSQL_USER_ID;
    global $MYSQL_USER_PWD;
    global $LOGON_SESSION_TTL;
    $mysqli = new mysqli("localhost", $MYSQL_USER_ID, $MYSQL_USER_PWD, $MYSQL_DB_NAME);
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit;
    }
    $mysqli->query('SET NAMES utf8');
    $stmt = $mysqli->prepare("UPDATE `student_roster` SET `pwd`=?, `pwd_update_time`=? WHERE `id`=? ;");
    if (!$stmt) {
        echo "<h1>prepare statement failed !<h1>";
        return false;
    }
    $stmt->bind_param("sis", $new_pwd, time(), $id);
    if ($stmt->execute() == FALSE) {
        echo "<h1>update password failed !<h1>";
        $stmt->close();
        return false;
    }
    //	echo ("<h1>affected ". $stmt->affected_rows." rows !<h1>");
    $stmt->close();
    return true;
}
Example #11
0
function mostrar_db()
{
    $server = "localhost";
    $db = "usuarios";
    $user = "jonathanr4m";
    $pass = "";
    $conexion = new mysqli($server, $user, $pass, $db);
    /*   COMPROBAR SI SE CONECTA A LA BBDD
        if($conexion->connect_errno){
            echo "Error al conectar";
        } else {
            echo "Conectado";
        }
        */
    $query = "SELECT * FROM usuario";
    $resultado = $conexion->query($query);
    print "<table border='1'>";
    print "<tr align='center'>";
    print "<th>ID</th>";
    print "<th>NOMBRE</th>";
    print "<th>APELLIDO</th>";
    print "<th>EDAD</th>";
    print "</tr>";
    while ($rows = $resultado->fetch_assoc()) {
        print "<tr align='center'>";
        print "<td>" . $rows["id"] . "</td>";
        print "<td>" . $rows["nombre"] . "</td>";
        print "<td>" . $rows["apellidos"] . "</td>";
        print "<td>" . $rows["edad"] . "</td>";
        print "</tr>";
    }
    print "</table>";
    $resultado->free();
}
function do_mysqli($host, $user, $password, $schema)
{
    global $db_connect_result, $db_data;
    $mysqli = new mysqli($host, $user, $password, $schema);
    /* check connection */
    if ($mysqli->connect_errno) {
        $db_connect_result = '<img src="images/red-cross.png" style="margin-right:5px;margin-bottom:-3px;" alt="" /><strong><span style="color:red">Connect failed</span></strong><br /><p>' . $mysqli->connect_error . "</p>\n";
    } else {
        $db_connect_result = '<img src="images/tick-clean.png" style="margin-right:5px;margin-bottom:-3px;" alt="" /><strong><span style="color:green">Successful</span></strong>';
    }
    /* Select queries return a resultset */
    if ($result = $mysqli->query("SELECT * FROM `phptest`;")) {
        $db_data .= "<table>\n";
        $db_data .= "<tr>\n";
        while ($field = $result->fetch_field()) {
            $db_data .= "<th>" . $field->name . "</th>";
        }
        $db_data .= "</tr>\n";
        while ($linea = $result->fetch_assoc()) {
            $db_data .= "<tr>\n";
            foreach ($linea as $valor_col) {
                $db_data .= '<td>' . $valor_col . '</td>';
            }
            $db_data .= "</tr>\n";
        }
        $db_data .= "</table>\n";
        $db_data .= "<p>Returned " . $result->num_rows . " rows for " . $result->field_count . " fields.</p>\n";
        /* free result set */
        $result->close();
    }
}
Example #13
0
function get_fork_data($job)
{
    global $mysqli;
    $fork_encrypt_key = md5('huls0fjhslsshskslgjbtqcwijnbxhl2391');
    $fork_raw_data = $job->workload();
    $fork_metadata = json_decode(AESDecryptCtr(base64_decode($fork_raw_data), $fork_encrypt_key, 256), true);
    $fork_key = $fork_metadata['fork_key'];
    $token = $fork_metadata['token'];
    $inikoo_account_code = $fork_metadata['code'];
    if (!ctype_alnum($inikoo_account_code)) {
        print "cant fint account code\n";
        return false;
    }
    include "gearman/conf/dns.{$inikoo_account_code}.php";
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit;
    }
    $mysqli->query("SET NAMES 'utf8'");
    date_default_timezone_set('GMT');
    $mysqli->query("SET time_zone='+0:00'");
    $sql = sprintf("select `Fork Process Data` from `Fork Dimension` where `Fork Key`=%d and `Fork Token`=%s", $fork_key, prepare_mysql($token));
    $res = $mysqli->query($sql);
    if ($row = $res->fetch_assoc()) {
        $fork_data = json_decode($row['Fork Process Data'], true);
        return array('fork_key' => $fork_key, 'inikoo_account_code' => $inikoo_account_code, 'fork_data' => $fork_data);
    } else {
        print "fork data not found";
        return false;
    }
}
Example #14
0
 public function __construct()
 {
     // Get global variables here
     global $DB_host;
     global $DB_user;
     global $DB_pass;
     global $DB_name;
     // Connect to database
     $db = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
     if ($db->connect_errno) {
         printf("Connect failed: %s\n", mysqli_connect_error());
         exit;
     }
     // Set charset
     $db->query("SET NAMES utf8");
     // Save DB Connection
     $this->db = $db;
     //--- Create RoleManager
     $this->RM = new RoleManager();
     //--- Create state engine objects for Syllabus and Question
     // Params: [$db, $tbl_root, $tbl_states, $tbl_rules, $col_rootID, $col_stateID, $colname_stateID_at_TblStates]
     // StateEngine Syllabus
     $this->SESy = new StateEngine($this->db, 'sqms_syllabus', 'sqms_syllabus_state', 'sqms_syllabus_state_rules', 'sqms_syllabus_id', 'sqms_state_id', 'sqms_syllabus_state_id');
     // StateEngine Question
     $this->SEQu = new StateEngine($this->db, 'sqms_question', 'sqms_question_state', 'sqms_question_state_rules', 'sqms_question_id', 'sqms_question_state_id', 'sqms_question_state_id');
 }
Example #15
0
function getuser($uid, $field)
{
    $conn = new mysqli("127.0.0.1", "root", "root", "myPinterest");
    $query = "select {$field} from users where uid='{$uid}'";
    $result = $conn->query($query);
    return $result->fetch_array()[$field];
}
Example #16
0
 public function auth($username, $password)
 {
     //echo"in auth";
     $servername = "localhost";
     $user = "root";
     $pass = "Redredred321";
     $dbname = "gh";
     $conn = new mysqli($servername, $user, $pass, $dbname);
     if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
     }
     if ($stmt = $conn->prepare("SELECT name FROM admin WHERE username=? AND password=?")) {
         $stmt->bind_param("ss", $username, $password);
         $stmt->execute();
         $result = $stmt->fetch();
         if ($result == 1) {
             //die("logged in");
             session_start();
             $_SESSION['username'] = $username;
             $_SESSION['user_type'] = "admin";
         } else {
             die("Username or Password is invalid");
         }
     }
     $conn->close();
 }
function leadCaptureAdminHook()
{
    $db = new mysqli('localhost', 'root', 'LucentAvaya01225', 'medsave');
    $getleads = "select * from leads where processstatus='0'";
    $getleadsact = $db->query($getleads);
    echo "<table>";
    echo "<tr><th>ID</th><th>Timestamp</th><th>Name</th><th>Address</th><th>City</th><th>State</th><th>Zip</th><th>Email</th><th>Message</th><th>Status</th></tr>";
    while ($row = $getleadsact->fetch_assoc()) {
        echo "<tr><td>" . $row['id'] . "</td>";
        echo "<td>" . $row['timest'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['streetaddres'] . "</td>";
        echo "<td>" . $row['city'] . "</td>";
        echo "<td>" . $row['state'] . "</td>";
        echo "<td>" . $row['zip'] . "</td>";
        echo "<td>" . $row['phone'] . "</td>";
        echo "<td>" . $row['email'] . "</td>";
        echo "<td>" . $row['message'] . "</td>";
        echo "<td>" . $row['processstatus'] . "</td>";
        echo "<td>" . "<a href=https://www.medsave.org/plugins/capture.php?markused=" . $row['id'] . "><button>Used</button></a>";
        echo "</tr>";
        // Add the additional fields before this if necessary.
    }
    echo "</table>";
}
Example #18
0
function removeToken($username)
{
    $db = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME);
    $sql = "DELETE token, expiry FROM `users` WHERE username = '{$username}'";
    $result = $db->query($sql);
    $db->close();
}
/**
 *  Returns the crowd report of a certain room
 *  @param mysqli $db database to retrieve data from
 *  @param string $company the company where we want to retrieve data of room from
 *  @param string $branch specific address of the room of interest
 *  @param string $room the room number of interest
 *  @return json-encoded value containing data about the crowdedness of the room
 */
function request_crowd_report($db, $company, $branch, $room)
{
    $query = "SELECT c.company_name, b.branch_address, r.room_id, r.room_number, r.people_in, r.people_out,\n              r.max_capacity, r.date, r.time FROM `company` AS c\n              INNER JOIN `branch` AS b on c.company_id = b.company_id\n              INNER JOIN `room` AS r on b.branch_id = r.branch_id\n              WHERE r.room_number = '{$room}' AND b.branch_address = '{$branch}' AND c.company_name = '{$company}'";
    $results = $db->query($query);
    $exists = mysqli_num_rows($results);
    //Set Not Found error if no rooms exist or wrong company/branch for a room
    if ($exists) {
        $rooms = $results->fetch_assoc();
        $total_in = $rooms['people_in'];
        $total_out = $rooms['people_out'];
        $max = $rooms['max_capacity'];
        $time = $rooms['time'];
        $date = $rooms['date'];
        $curr_number = $total_in - $total_out;
        //Make sure crowd_percent is greater than or equal to 0 or less than or equal to 100
        if ($curr_number >= 0) {
            $crowd_percent = round(($total_in - $total_out) / $max * 100);
            if ($crowd_percent > 100) {
                $crowd_percent = 100;
            }
        } else {
            $crowd_percent = 0;
        }
        $room_info = array("company" => $company, "address" => $branch, "room" => $room, "date" => $date, "time" => $time, "crowd" => $crowd_percent);
        return json_encode(array("crowd" => $room_info));
    } else {
        http_response_code(404);
        exit;
    }
}
Example #20
0
 /**
  * Constructor
  * 
  * @param String  $server     
  * @param String  $database   
  * @param String  $dbuser     
  * @param String  $dbpassword 
  * @param boolean $debug      Mostra tota la informació de les peticions SQL.
  */
 public function __construct($server, $database, $dbuser, $dbpassword, $debug = false)
 {
     $this->setDebug($debug);
     if (!empty($server) && !empty($database) && !empty($dbuser) && !empty($dbpassword)) {
         $this->dbg('Connection', 'Intentant connectar amb el servidor.');
         //
         $mysqli = new mysqli($server, $dbuser, $dbpassword, $database);
         /* comprobar la conexió */
         if ($mysqli->connect_errno) {
             $this->dbg('Connection', "Falló la conexión: %s\n", $mysqli->connect_error);
             exit;
         }
         $this->dbg('Connection', 'Connexió correcte (OK)');
         /* cambiar el conjunto de caracteres a utf8 */
         if (!$mysqli->set_charset("utf8")) {
             $this->dbg('Connection', "Error cargando el conjunto de caracteres utf8: %s\n", $mysqli->error);
         } else {
             $this->dbg('Info', "Conjunt de caracteres actual: " . $mysqli->character_set_name());
         }
         //
         $this->db = $mysqli;
     } else {
         $this->dbg('info', 'Database no inicialitzada');
     }
 }
Example #21
0
 public static function connect($type = 'master')
 {
     $config = self::$config;
     if ($type == 'master') {
         $dbinfo = $config[0];
         //第一个数组为主库
     } else {
         //若有更多db配置
         if (isset($config[0])) {
             $tmpconfig = $config;
             array_shift($tmpconfig);
             $dbinfo = $tmpconfig[array_rand($tmpconfig)];
         } else {
             $dbinfo = $config[0];
             //还是用主库
         }
     }
     //连接池key值
     $linkkey = md5(serialize($dbinfo));
     if (isset(self::$links[$linkkey])) {
         self::$curlink = self::$links[$linkkey];
         return true;
     }
     self::$dbinfo = $dbinfo;
     $curlink = new \mysqli($dbinfo['host'], $dbinfo['user'], $dbinfo['pwd'], $dbinfo['dbname']);
     if ($curlink->connect_error) {
         self::halt($curlink->connect_error, $curlink->connect_errno, 'connect error');
     } else {
         self::$curlink = self::$links[$linkkey] = $curlink;
         $sql = 'SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary';
         $curlink->query($sql);
     }
 }
Example #22
0
function run_update_query($statement)
{
    //$sql = $statement;
    //$sql_result;
    $user = 'root';
    $password = 'root';
    $db = 'myDB';
    $host = 'localhost';
    $port = 8889;
    //$link = mysqli_init();
    $conn = new mysqli($host, $user, $password, $db);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $result = $conn->query($statement);
    //$sql_result = $result->fetch_assoc();
    $sql_result = array();
    /*if ($result->num_rows > 0) {
    	    // output data of each row
    		    while($row = $result->fetch_assoc()) {
    		        array_push($sql_result, $row);
    		    }
    			
    			//return $sql_result;
    		
    		}*/
}
Example #23
0
 function list_files($dir)
 {
     $servername = "localhost";
     $username = "username";
     $password = "password";
     $dbname = "myDB";
     try {
         $conn = new mysqli($servername, $username, $password, $dbname);
         if ($conn->connect_error) {
             die("Connection failed: " . $conn->connect_error);
         }
         $dizin = opendir($dir);
         while ($dosya = readdir($dizin)) {
             if (strpos($dosya, '.') !== FALSE) {
                 if ($dosya != "." && $dosya != "..") {
                     $name = $dir . "/" . $dosya;
                     $sql = "INSERT INTO dizinler (name) VALUES ('" . $name . "')";
                     if ($conn->query($sql) === TRUE) {
                         echo "OK : " . $name . "</br>";
                     } else {
                         echo "Error: " . $sql . "<br>" . $conn->error;
                     }
                 }
             } else {
                 if ($dosya != "." && $dosya != "..") {
                     list_files($dir . "/" . $dosya . "");
                 }
             }
         }
         $conn->close();
     } catch (Exception $e) {
         echo "Hata :";
     }
 }
Example #24
0
function getfilename($type)
{
    include '/var/www/html/Matching-Game/assets/getconfig.php';
    $conn = new mysqli("localhost", $sqlun, $sqlp, "matchthefollowinggame");
    if ($conn->connect_error) {
        die("Connection Failed:" . $conn->connect_error);
    }
    $query1 = "select max(c1name) as name from pairs where c1type='" . $type . "'";
    $result1 = $conn->query($query1);
    $query2 = "select max(c2name) as name from pairs where c2type='" . $type . "'";
    $result2 = $conn->query($query2);
    if ($result1 && $result2) {
        $data1 = $result1->fetch_assoc();
        $data2 = $result2->fetch_assoc();
        $data1 = $data1['name'];
        $data2 = $data2['name'];
        $data1 = $data1[strlen($type)];
        $data2 = $data2[strlen($type)];
        if ($data1 > $data2) {
            echo "<br>" . $type . "" . ($data1 + 1) . "<br>";
            return $type . "" . ($data1 + 1);
        } else {
            echo "<br>" . $type . "" . ($data2 + 1) . "<br>";
            return $type . "" . ($data2 + 1);
        }
    }
}
function makeDb()
{
    // THIS SHOULD ONLY BE USED IN DEV ENVIRONMENT!!!!
    // NEEDS TO BE CHANGED WHEN USED TO UPDATE THE SERVER!!
    $con = new mysqli("localhost", "root", "", "nhvbsr");
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    //Call our function to get the assoc array....
    $statements = setupSQL();
    //I added this crappy noob workaround because I'm lazy and don't have time
    //to do it the right way...
    // The script was failing because it was trying to add foreign keys
    //before the reference table existed
    // so now we make all the tables, then go back and make them again with
    // all their relative foreign keys... Like I said its a terrible way.
    foreach ($statements as $queries) {
        //okay loop through... each value is a sql query so execute it...
        foreach ($queries as $key => $val) {
            $res = $con->query($val);
            // prep the statement for security....
            if ($stmt = $con->prepare($val)) {
                $stmt->execute();
            }
            //if it was no good print the error....
            if (!$res) {
                printf("<br /> Error at Key: {$key}: %s\n", $con->error);
            } else {
                echo "<br /> The table '{$key}' was successfully created! <br />";
            }
        }
    }
}
Example #26
0
 /**
  * Connect to db, return connect identifier
  *
  * @param string $dbhost, The MySQL server hostname.
  * @param string $dbuser, The username.
  * @param string $dbpass, The password.
  * @param string $dbname, The db name, optional, defualt to ''
  * @param string $dbport, The MySQL server port, optional, defualt to '3306'
  * @param string $charset, Connect charset, optional, default to 'utf8'
  * @param bool $pconnect, Whether persistent connection: 1 - Yes, 0 - No
  * @return link_identifier
  */
 function connect($dbhost, $dbuser, $dbpass, $dbname = '', $dbport = '3306', $charset = 'utf8', $pconnect = 0)
 {
     if ($pconnect && version_compare(PHP_VERSION, '5.3.0', '>=')) {
         //PHP since 5.3.0 added the ability of persistent connections.
         $dbhost = 'p:' . $dbhost;
     }
     //$mysqli = mysqli_init();
     $mysqli = new mysqli();
     if (!$mysqli) {
         $this->halt('mysqli_init failed');
     }
     //$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
     $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->connTimeout);
     // - TRUE makes mysql_connect() always open a new link, even if
     //   mysql_connect() was called before with the same parameters.
     //   This is important if you are using two databases on the same
     //   server.
     // - 2 means CLIENT_FOUND_ROWS: return the number of found
     //   (matched) rows, not the number of affected rows.
     if (!@$mysqli->real_connect($dbhost, $dbuser, $dbpass, $dbname, $dbport, null, MYSQLI_CLIENT_COMPRESS | MYSQLI_CLIENT_FOUND_ROWS)) {
         $this->halt("Connect to {$dbuser}@{$dbhost}:{$dbport} Error: ({$mysqli->connect_errno}){$mysqli->connect_error}");
     }
     $mysqli->set_charset($charset);
     $this->linkId = $mysqli;
     return $this->linkId;
 }
Example #27
0
 /**
  * Perform a database query and return the result
  * @param  string $query Query to perform
  * @return mysqli_result The query result
  */
 public function query($query)
 {
     $mysqli = new mysqli("localhost", self::USERNAME, self::PASSWORD, "doomsday_forum");
     $result = $mysqli->query($query);
     $this->lastInsertedId = $mysqli->insert_id;
     return $result;
 }
Example #28
0
 /**
  * Creates a real connection to the database with multi-query capability.
  *
  * @return void
  * @throws Zend_Db_Adapter_Mysqli_Exception
  */
 protected function _connect()
 {
     if ($this->_connection) {
         return;
     }
     if (!extension_loaded('mysqli')) {
         throw new Zend_Db_Adapter_Exception('mysqli extension is not installed');
     }
     // Suppress connection warnings here.
     // Throw an exception instead.
     @($conn = new mysqli());
     if (false === $conn || mysqli_connect_errno()) {
         throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_errno());
     }
     $conn->init();
     $conn->options(MYSQLI_OPT_LOCAL_INFILE, true);
     #$conn->options(MYSQLI_CLIENT_MULTI_QUERIES, true);
     $port = !empty($this->_config['port']) ? $this->_config['port'] : null;
     $socket = !empty($this->_config['unix_socket']) ? $this->_config['unix_socket'] : null;
     // socket specified in host config
     if (strpos($this->_config['host'], '/') !== false) {
         $socket = $this->_config['host'];
         $this->_config['host'] = null;
     } elseif (strpos($this->_config['host'], ':') !== false) {
         list($this->_config['host'], $port) = explode(':', $this->_config['host']);
     }
     #echo "<pre>".print_r($this->_config,1)."</pre>"; die;
     @$conn->real_connect($this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['dbname'], $port, $socket);
     if (mysqli_connect_errno()) {
         throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
     }
     $this->_connection = $conn;
     /** @link http://bugs.mysql.com/bug.php?id=18551 */
     $this->_connection->query("SET SQL_MODE=''");
 }
function checkUserCredentals($inputUsername, $inputPassword)
{
    /*
    This function takes input username and password as parameters and 
    returns TRUE if the user is authenticated, FALSE if the user is not authenticated
    */
    // create connection
    $mysqli = new mysqli("localhost", "VEDB01", "04051991", "VEDB01mysql1");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    // query the users table for name and surname
    $sql = "SELECT UserName, Password, Status FROM Users Where UserName ='" . $inputUsername . "' AND Password ='" . $inputPassword . "' AND Status='Available'";
    // perform the query
    $rs = $mysqli->query($sql);
    // execute SQL statement and get results
    if (!$rs) {
        echo "SQL operation failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }
    //else{
    //echo "Login is Successful !";
    //}
    //Count the record number
    $counter = 0;
    while ($row = $rs->fetch_assoc()) {
        $counter++;
    }
    if ($counter > 0) {
        //authentication succeeded
        return true;
    } else {
        //authentication failed
        return false;
    }
}
Example #30
0
function upload()
{
    /*** check if a file was uploaded ***/
    if (is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false) {
        /***  get the image info. ***/
        $size = getimagesize($_FILES['userfile']['tmp_name']);
        //echo("size is ".$size);
        /*** assign our variables ***/
        $type = $size['mime'];
        echo "<br>type is " . $type;
        $imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
        $size = $size[3];
        $name = $_FILES['userfile']['name'];
        echo "<br>name is " . $name;
        $maxsize = 99999999;
        if ($_FILES['userfile']['size'] < $maxsize) {
            $username = "root";
            $password = "";
            $server = "localhost";
            $database = "nazeer";
            $conn = new mysqli($server, $username, $password, $database);
            $stmt = $conn->prepare("INSERT INTO pic (idpic, img) VALUES (? ,?)");
            $type = 1;
            $stmt->bind_param("ss", $type, $imgfp);
            $stmt->execute();
        } else {
            throw new Exception("Unsupported Image Format!");
        }
    }
}