Example #1
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);
        }
    }
}
    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 #3
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 #4
0
function loadData($request)
{
    global $hostname_ISANdb;
    global $database_ISANdb;
    global $username_ISANdb;
    global $password_ISANdb;
    $mysqli = new mysqli($hostname_ISANdb, $username_ISANdb, $password_ISANdb, $database_ISANdb);
    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
    }
    $mysqli->query("SET NAMES 'UTF8'");
    if ($request == "person") {
        if ($stmt = $mysqli->prepare("SELECT id, firstName, lastName, patrName FROM `{$request}` WHERE 1")) {
            $stmt->execute();
            $stmt->bind_result($id, $fname, $lname, $pname);
            while ($stmt->fetch()) {
                $result .= "<option value=\"{$id}\">{$lname} {$fname} {$pname}</option>";
            }
            $mysqli->close();
            return $result;
        }
    }
    if ($stmt = $mysqli->prepare("SELECT id, name FROM `{$request}` WHERE 1")) {
        $stmt->execute();
        $stmt->bind_result($id, $name);
        $result = "<option value=\"0\">Не выбрано</option>";
        while ($stmt->fetch()) {
            $result .= "<option value=\"{$id}\">{$name}</option>";
        }
        $mysqli->close();
        return $result;
    }
}
Example #5
0
function getClassi($idClasse)
{
    // Create connection
    $conn = new mysqli(AIRO_CONN_SERVERNAME, AIRO_CONN_USERNAME, AIRO_CONN_PASSWORD, AIRO_CONN_DBNAME);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    // preparazione dello statement SQL
    // se il parametro è null, viene scelto uno statement SQL senza criteri di filtro.
    if (is_null($idClasse)) {
        $stmt = $conn->prepare(AIRO_SQL_GET_CLASSI_ALL);
    } else {
        $stmt = $conn->prepare(AIRO_SQL_GET_CLASSI_BY_ID);
        $stmt->bind_param("s", $idClasse);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $esito = "";
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $esito = $row['DescrizioneClasse'];
    }
    $conn->close();
    return $esito;
}
Example #6
0
function authenticateUser($username, $password)
{
    $con = new mysqli('localhost', 'root', 'rooty', 'glossary');
    $Squery = "SELECT `password_salt` FROM `users` WHERE `username` = ? OR `email` = ?";
    $Sstmt = $con->prepare($Squery);
    $Sstmt->bind_param('ss', $username, $password);
    $Sstmt->execute();
    $Sstmt->bind_result($salt);
    while ($Sstmt->fetch()) {
        $salt = $salt;
    }
    $password_hash = sha1($password . $salt);
    $Lquery = "SELECT `user_id`, `user_type`, `full_name` FROM `users` WHERE (`username` = ? OR `email` = ?) AND `password_hash` = ?";
    $Lstmt = $con->prepare($Lquery);
    $Lstmt->bind_param('sss', $username, $email, $password_hash);
    $Lstmt->execute();
    $Lstmt->bind_result($user_id, $user_type, $full_name);
    while ($Lstmt->fetch()) {
        $user_id = $user_id;
        $user_type = $user_type;
        $full_name = $full_name;
    }
    if (!is_null($user_id)) {
        $_SESSION['user_id'] = $user_id;
        $_SESSION['user_type'] = $user_type;
        $_SESSION['username'] = $username;
        $_SESSION['full_name'] = $full_name;
        return true;
    } else {
        return false;
    }
}
Example #7
0
 /**
  * Delete model by id.
  *
  * @param ModelBase $model
  * @throws ControllerException
  */
 protected function _deleteModelById($sql, $model)
 {
     if ($model->validateForDelete()) {
         $stmt = $this->_dbh->prepare($sql);
         if (!$stmt) {
             throw new ControllerException('Prepared statement failed for ' . $sql);
         }
         $id = $model->getId();
         if (!$stmt->bind_param('i', $id)) {
             throw new ControllerException('Binding parameters for prepared statement failed.');
         }
         if (!$stmt->execute()) {
             throw new ControllerException('Failed to execute DELETE statement. (' . $this->_dbh->error . ')');
         }
         /**
          * @SuppressWarnings checkAliases
          */
         if (!$stmt->close()) {
             throw new ControllerException('Something broke while trying to close the prepared statement.');
         }
         return;
     } else {
         throw new ControllerException('Invalid data');
     }
 }
function registerPlayer($xml)
{
    global $sqlhost, $sqlusername, $sqlpassword;
    #Check if registration credentials are valid.
    if ($xml->username == null or $xml->password == null) {
        error_log("registerPlayer.php - Registration rejected");
        return false;
    } else {
        #Clean up registration credentials.
        $tempUsername = preg_replace("/[^A-Za-z0-9]/", '', $xml->username);
        $tempPassword = preg_replace("/[^A-Za-z0-9]/", '', $xml->password);
        #Validate that username and password are legal.
        if (strlen($xml->username) == 0) {
            return false;
        } else {
            if (strlen($xml->password) == 0) {
                return false;
            } else {
                if ($tempUsername !== (string) $xml->username) {
                    return false;
                } else {
                    if ($tempPassword !== (string) $xml->password) {
                        return false;
                    } else {
                        $conn = new mysqli($sqlhost, $sqlusername, $sqlpassword);
                        if ($conn->connect_error) {
                            error_log("registerPlayer.php - Connection failed: " . $conn->connect_error);
                            return false;
                        }
                        #Check if username already taken
                        if ($checkStmt = $conn->prepare("SELECT COUNT(*) FROM sweepelite.players WHERE username=?")) {
                            $checkStmt->bind_param("s", $xml->username);
                            $checkStmt->execute();
                            $checkStmt->bind_result($count);
                            $checkStmt->close();
                            if ($count == 0) {
                                #Register the player in the MySQL database.
                                if ($registerStmt = $conn->prepare("INSERT INTO sweepelite.players (username, password, salt) VALUES (?,?,?)")) {
                                    $salt = sec_getNewSalt();
                                    $saltedPW = sec_getHashedValue($xml->password, $salt);
                                    $registerStmt->bind_param("sss", $xml->username, $saltedPW, $salt);
                                    $registerStmt->execute();
                                    if ($registerStmt->affected_rows > 0) {
                                        return true;
                                    } else {
                                        error_log("registerPlayer.php - Unable to register player.");
                                    }
                                }
                            }
                        } else {
                            error_log("registerPlayer.php - Unable to prepare statement for checking registration.");
                        }
                    }
                }
            }
        }
    }
    return false;
}
 public function addAchievements()
 {
     /* @var $stmt mysqli_stmt */
     $stmt = $this->db->prepare("INSERT INTO `achievements` (`user_id`, `count`) VALUES (?, 1)\r\n            ON DUPLICATE KEY UPDATE `count` = `count` + 1");
     $stmt->bind_param('s', $this->userid);
     $stmt->execute();
     return $this->getAchievements();
 }
Example #10
0
function clear_uploads()
{
    $db = new mysqli(getenv('HOST_IP'), 'root', getenv('MYSQL_ROOT_PASSWORD'), getenv('WORDPRESS_DATABASE'));
    $statement = $db->prepare("DELETE wp_postmeta FROM wp_postmeta JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id WHERE wp_posts.post_type = 'attachment'");
    $statement->execute();
    $statement = $db->prepare("DELETE FROM wp_posts WHERE wp_posts.post_type = 'attachment'");
    $statement->execute();
    shell_exec('docker exec -it wordpress' . getenv('WORDPRESS_VERSION') . ' rm -rf wp-content/uploads');
}
Example #11
0
 public function insertReport(CrashReport $report)
 {
     if ($stmt = $this->db->prepare(self::$INSERT_REPORT)) {
         $stmt->bind_param("ssississiii", $report->getCausingPlugin(), $report->getVersion()->get(true), $report->getVersion()->getBuild(), $report->getFile(), $report->getMessage(), $report->getLine(), $report->getType(), $report->getOS(), $report->getReportType(), time(), $report->getDate());
         $stmt->execute();
         return $this->db->insert_id;
     }
     return -1;
 }
 private function checkPreparedStatement($queryname, $sql)
 {
     if (!isset($this->db_statements[$queryname])) {
         $this->db_statements[$queryname] = $this->db->prepare($sql);
     }
     if ($this->db_statements[$queryname] === false) {
         $this->criticalError("Database error preparing query for  " . $queryname . ": " . $this->db->error);
         return false;
     }
     return true;
 }
Example #13
0
 /**
  * @param query $query
  * @return query
  */
 public function execute($query)
 {
     $stmt = $this->resource->prepare($query->getQueryString());
     foreach ($query->getArguments() as $value) {
         $stmt->bind_param($value['type'], $value['argument']);
     }
     $stmt->execute();
     $result = $stmt->get_result();
     $query->setResult($result->fetch_all())->setAffectedRows($stmt->affected_rows)->setInsertId($this->resource->insert_id);
     $stmt->close();
     $result->close();
     return $query;
 }
Example #14
0
 /**
  * @param string $session_id
  * @param string $session_data
  * @return bool|void
  */
 public function write($session_id, $session_data)
 {
     $now = time();
     if ($this->read($session_id) === '') {
         $stmt = $this->connection->prepare("INSERT INTO session_store(session_id, session_data, updated_at) VALUES (?, ?, ?)");
         $stmt->bind_param("ssd", $session_id, $session_data, $now);
         $stmt->execute();
         $stmt->close();
     } else {
         $stmt = $this->connection->prepare("UPDATE session_store SET session_data=?, updated_at=? WHERE session_id=?");
         $stmt->bind_param("sds", $session_data, $now, $session_id);
         $stmt->execute();
         $stmt->close();
     }
 }
Example #15
0
 function connect()
 {
     $host = 'localhost';
     $user = 'barril1_MyUser';
     $password = 'illini';
     $dbName = 'barril1_ProjectComments';
     $dbconn = new mysqli($host, $user, $password, $dbName);
     $tableExists = $dbconn->prepare("SELECT * FROM {$this->projectID}");
     if (!$tableExists) {
         $query = "CREATE TABLE {$this->projectID}(Name VARCHAR(25), Comment VARCHAR(255))";
         $stmt = $dbconn->prepare($query);
         $stmt->execute();
     }
     return $dbconn;
 }
Example #16
0
 public function fetch($sql, $type = Aix_Db_Adapter::FETCH_ASSOC, $offset = 0, $length = null)
 {
     if (!in_array($type, array(Aix_Db_Adapter::FETCH_ASSOC, Aix_Db_Adapter::FETCH_ARRAY))) {
         throw new Aix_Db_Exception('Fetch type not supported');
     }
     if ($stmt = $this->connection->prepare($sql)) {
         $results = array();
         $stmt->execute();
         $stmt->store_result();
         $assoc = array();
         $array = array();
         $meta = $stmt->result_metadata();
         while ($field = $meta->fetch_field()) {
             $array[] =& $assoc[$field->name];
         }
         call_user_func_array(array($stmt, 'bind_result'), $array);
         $offset = null === $offset ? 0 : intval($offset);
         $length = null === $length ? 0 : intval($length);
         $i = -1;
         while ($stmt->fetch()) {
             $i++;
             if ($i < $offset) {
                 continue;
             }
             switch ($type) {
                 case Aix_Db_Adapter::FETCH_ASSOC:
                     $results[] = array_map(create_function('$a', 'return "$a";'), $assoc);
                     break;
                 case Aix_Db_Adapter::FETCH_ARRAY:
                     $results[] = array_map(create_function('$a', 'return "$a";'), $array);
                     break;
                 case Aix_Db_Adapter::FETCH_OBJECT:
                     // break;
                 // break;
                 default:
                     throw new Aix_Db_Exception('Fetch type not supported');
                     break;
             }
             if ($length > 0 && $i >= $offset + $length) {
                 break;
             }
         }
         $meta->close();
         $stmt->close();
         return $results;
     }
     throw new Aix_Db_Exception($this->connection->error);
 }
Example #17
0
 /**
  * Выполняет запрос в базу и возвращает результат в виде ассоциативного массива
  * @param  string Запрос для prepare
  * @param  array Переменные запроса [type => value]
  * @param  string Поле для индекса массива
  * @return array
  */
 public function query($query = null, $vars = null, $fieldArrayIndex = false)
 {
     $noExecute = false;
     if (!is_null($query)) {
         if (is_array($query)) {
             $noExecute = true;
             $query = $query[0];
         }
         $stmt = $this->connect->prepare($query);
         $this->lastStmt = $stmt;
         if (false === $stmt) {
             var_dump(['query' => $query, 'args_json' => json_encode($vars)]);
             die('prepare() failed: ' . $this->connect->error);
         } else {
             if (false === is_null($vars) && count($vars)) {
                 $types = array();
                 foreach ($vars as $k => $v) {
                     $types[] = $v[0];
                 }
                 $types = implode($types);
                 $args = array($stmt, $types);
                 $this->lastVars = [];
                 foreach ($vars as $k => $v) {
                     $this->lastVars[$k] = $v[1];
                     $args[] =& $this->lastVars[$k];
                 }
                 call_user_func_array(mysqli_stmt_bind_param, $args);
             }
         }
     } else {
         $stmt = $this->lastStmt;
         foreach ($vars as $k => $v) {
             $this->lastVars[$k] = $v;
         }
     }
     if (!$noExecute) {
         $stmt->execute();
         $result = array();
         while ($row = $this->stmtRowAssoc($stmt)) {
             if (false === $fieldArrayIndex) {
                 $result[] = $row;
             } else {
                 $result[$row[$fieldArrayIndex]] = $row;
             }
         }
         return $result;
     }
 }
Example #18
0
function getFeaturedEvent($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE)
{
    $query = 'SELECT tiles.start_date, tiles.end_date, tiles.title, types.title as type_title, categories.title AS category_title, ';
    $query .= 'tiles.image_thumb, tiles.image_large, tiles.alt, tiles.id FROM tiles ';
    $query .= 'JOIN types ON (tiles.type_id = types.id) ';
    $query .= 'LEFT OUTER JOIN categories ON (tiles.category_id = categories.id) ';
    $query .= 'WHERE tiles.is_feature_event = 1';
    $mysqli = new mysqli($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
    $stmt = $mysqli->prepare($query);
    $stmt->execute();
    $stmt->bind_result($start_date, $end_date, $title, $type_title, $category_title, $image_thumb, $image_large, $alt, $tile_id);
    $results = array();
    $i = 0;
    while ($stmt->fetch()) {
        $results[$i]['start_date'] = $start_date;
        $results[$i]['end_date'] = $end_date;
        $results[$i]['title'] = $title;
        $results[$i]['type_title'] = $type_title;
        $results[$i]['category_title'] = $category_title;
        $results[$i]['image_thumb'] = $image_thumb;
        $results[$i]['image_large'] = $image_large;
        $results[$i]['alt'] = $alt;
        $results[$i]['tile_id'] = $tile_id;
        $i++;
    }
    $stmt->close();
    $mysqli->close();
    return $results;
}
Example #19
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();
 }
Example #20
0
function getGameChat($lastUpdateTime = 0, $ignoreUpdateTime = false)
{
    global $sqlhost, $sqlusername, $sqlpassword;
    $ret = "<chatlog>";
    $conn = new mysqli($sqlhost, $sqlusername, $sqlpassword);
    if ($conn->connect_error) {
        error_log("getGameChat.php - Connection failed: " . $conn->connect_error);
        return "";
    }
    if ($ignoreUpdateTime) {
        $lastUpdateTime = 0;
    }
    $compDate = new DateTime();
    $compDate->setTimestamp($lastUpdateTime);
    $compDate = $compDate->format('Y-m-d H:i:s');
    if ($query = $conn->prepare("SELECT b.username, a.message, a.forCurrentGame FROM sweepelite.chatmessages as a INNER JOIN sweepelite.players as b ON a.playerID = b.playerID WHERE a.time > ? ORDER BY a.time DESC LIMIT 50")) {
        $query->bind_param("s", $compDate);
        $query->execute();
        $query->bind_result($username, $message, $isCurrent);
        while ($query->fetch()) {
            $temp = "<chat current='" . $isCurrent . "'>";
            $temp .= "<user>" . $username . "</user>";
            $temp .= "<msg>" . $message . "</msg>";
            $temp .= "</chat>";
            $ret .= $temp;
        }
        $query->close();
    }
    if (strlen($ret) > strlen("<chatlog>")) {
        $ret .= "</chatlog>";
        return $ret;
    }
    return "";
}
Example #21
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 #22
0
function set_siteurl($site_url)
{
    $db = new mysqli('mysql', 'root', getenv('MYSQL_ROOT_PASSWORD'), getenv('WORDPRESS_DATABASE'));
    $statement = $db->prepare("UPDATE wp_options SET option_value = ? WHERE option_name = 'home' OR option_name = 'siteurl'");
    $statement->bind_param('s', $site_url);
    $statement->execute();
}
Example #23
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!");
        }
    }
}
Example #24
0
	public function prepare($query) {
		if (Config::$IS_DEBUG)
			echo($query."<br/>");
		$this->aantal++;
		$_SESSION['numOfQ'] = $this->aantal;
		return parent::prepare($query);
	}
 /**
  * Prepares a sql query optionally as a prepared statement if the prepArgs
  * array is specified
  * @name query
  * @param str $sql SQL to execute
  * @param str $prepArgs Arguments for prepared statement queries
  * @since 0.1.0
  * @return object query results
  * <code>
  * <?php
  * $query = $db->query("select * from foo")
  *
  * //prepared (safe from injection)
  * $query = $db->query("select * from foo where foo_id = ?", ['i', 1]);
  *
  * ?>
  * </code>
  */
 public function query($sql, $prepArgs = false)
 {
     if (!$this->conn->ping()) {
         $this->conn->close();
         $this->connect();
     }
     try {
         if (is_array($prepArgs)) {
             $stmt = $this->conn->prepare($sql);
             if (false === $stmt) {
                 $this->error("Couldn't prepare statement: " . $this->conn->error);
             } else {
                 $method = new \ReflectionMethod('mysqli_stmt', 'bind_param');
                 $method->invokeArgs($stmt, $this->_mkrefs($prepArgs));
                 /* much love to jan kriedner */
                 $stmt->execute();
                 if ($stmt->insert_id > 0) {
                     $result = $stmt->insert_id;
                 } else {
                     $result = $stmt->get_result();
                 }
             }
         } else {
             $result = $this->conn->query($sql);
         }
     } catch (Exception $e) {
         $this->error($e->getMessage() . " SQL: {$sql}");
     }
     return $result;
 }
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 #27
0
function auth($username, $password)
{
    // Create connection
    $mysqli = new mysqli($servername, $user, $passwd, $database);
    // Check connection
    if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    }
    if ($stmt = $mysqli->prepare("SELECT COUNT(*), wa_nickname, wa_number, wa_key FROM config where username = ? and password = ?;")) {
        $stmt->bind_param("ss", $username, $password);
        $stmt->execute();
        $stmt->bind_result($userCount, $wa_nickname, $wa_number, $wa_key);
        $stmt->fetch();
        if ($userCount == 1) {
            $_SESSION['wa_nickname'] = $wa_nickname;
            $_SESSION['wa_number'] = $wa_number;
            $_SESSION['wa_key'] = $wa_key;
            $stmt->close();
            $mysqli->close();
            return true;
        } else {
            $stmt->close();
            $mysqli->close();
            return false;
        }
    }
    return false;
}
Example #28
0
function dbquery_func($connection_info, $query, $debug)
{
    if ($connection_info['db_type'] == "mysql") {
        if (!is_array($query)) {
            return FALSE;
        }
        $link = new mysqli($connection_info['db_host'], $connection_info['username'], $connection_info['password'], $connection_info['db_name'], $connection_info['db_port']);
        if ($link->connect_error) {
            die("Connection Error (" . $mysqli->connect_errno . ") - " . $mysqli->connect_error);
        }
        if ($stmt = $link->prepare($query['query'])) {
            call_user_func_array(array($stmt, 'bind_param'), refvalues($query['params']));
            $stmt->execute();
            $meta = $stmt->result_metadata();
            $parameters = array();
            $results = array();
            while ($field = $meta->fetch_field()) {
                $parameters[] =& $row[$field->name];
            }
            call_user_func_array(array($stmt, 'bind_result'), refvalues($parameters));
            while ($stmt->fetch()) {
                $x = array();
                foreach ($row as $key => $val) {
                    $x[$key] = $val;
                }
                $results[] = $x;
            }
            $stmt->close();
            $mysqli->close();
            return $result;
        }
    }
}
 /**
  * Method attempts to prepare the SQL query
  * and throws an error if there was a problem.
  *
  * @return mysqli_stmt
  */
 protected function _prepareQuery()
 {
     if (!($stmt = $this->_mysqli->prepare($this->_query))) {
         trigger_error("Problem preparing query ({$this->_query}) " . $this->_mysqli->error, E_USER_ERROR);
     }
     return $stmt;
 }
Example #30
0
function getAllData($keyword = "")
{
    $search = "";
    if ($keyword == "") {
        $search = "%%";
    } else {
        $search = "%" . $keyword . "%";
    }
    $mysqli = new mysqli($GLOBALS["servername"], $GLOBALS["server_username"], $GLOBALS["server_password"], $GLOBALS["database"]);
    $stmt = $mysqli->prepare("SELECT id, username, title, text, time FROM notes WHERE deleted IS NULL AND title IS NOT NULL AND (title LIKE ? OR text LIKE ?)");
    $stmt->bind_param("ss", $search, $search);
    $stmt->bind_result($id_from_db, $user_id_from_db, $title_from_db, $text_from_db, $time_from_db);
    $stmt->execute();
    $array = array();
    while ($stmt->fetch()) {
        $note = new StdClass();
        $note->id = $id_from_db;
        $note->title = $title_from_db;
        $note->username = $user_id_from_db;
        $note->text = $text_from_db;
        $note->time = $time_from_db;
        array_push($array, $note);
    }
    return $array;
    $stmt->close();
    $mysqli->close();
}