/**
  * (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 #2
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 = '******' AND 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;
        }
    }
}
 /**
  * @inheritdoc
  */
 public function escape($value)
 {
     if (!is_object($this->dbh)) {
         $this->connect();
     }
     return $this->dbh->real_escape_string($value);
 }
Example #4
0
function join_team($code)
{
    if (!isset($_SESSION['User'])) {
        return 'You must be logged in to join a team.';
    }
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $ecode = $conn->real_escape_string($code);
    $tquery = "SELECT * FROM `teams` WHERE teamcode='{$ecode}'";
    $res = $conn->query($tquery);
    if (!$res) {
        return 'Team with code does not exist.';
    }
    $data = $res->fetch_assoc();
    if (!$data) {
        return 'Team with code does not exist.';
    }
    $name = $data['name'];
    $ename = $conn->real_escape_string($name);
    $user = $_SESSION['User'];
    $euser = $conn->real_escape_string($user);
    $joinquery = "UPDATE `users` SET team='{$ename}' WHERE name='{$euser}'";
    $conn->query($joinquery);
    if ($conn->error) {
        return 'Failed to join team.';
    }
    return 'OK';
}
Example #5
0
    function __construct($metaphone, $gender, $count)
    {
        $this->mRecords = [];
        $db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
        $safe_metaphone = $db->real_escape_string($metaphone);
        $safe_gender = $db->real_escape_string($gender);
        $query = <<<QUERY
SELECT\tName,
\t\tSUM(NameCount) AS NameCount,
          SUM(Total) AS Total
FROM\t     names
JOIN \tname_counts ON NameId = FK_NameID
JOIN \tyear_gender_totals ON YearGenderTotalID = FK_YearGenderTotalID
WHERE\tMetaphone = '{$safe_metaphone}'
AND \t     Gender = '{$safe_gender}'
GROUP BY  Name
ORDER BY  CAST(SUM(NameCount) / SUM(Total) AS DECIMAL(18,16)) DESC
LIMIT 0, {$count};
QUERY;
        $results = $db->query($query);
        $recs = $results->fetch_all(MYSQLI_NUM);
        //          $name, $gender, $year, $rank, $count, $total, $metaphone
        foreach ($recs as $rec) {
            $name_popularity_rec = new NamePopularityRecord($rec[MetaphoneSet::NAME_FIELD], $gender, 0, 0, $rec[MetaphoneSet::COUNT_FIELD], $rec[MetaphoneSet::TOTAL_FIELD], $metaphone);
            $this->mRecords[] = $name_popularity_rec;
        }
    }
Example #6
0
    function __construct($year, $gender, $count)
    {
        $this->mRecords = [];
        $db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
        $safe_year = $db->real_escape_string($year);
        $safe_gender = $db->real_escape_string($gender);
        $safe_count = $db->real_escape_string($count);
        echo $count;
        $query = <<<QUERY
SELECT Name, Metaphone, Rank, NameCount, Year, Gender, Total
FROM NAMES
JOIN NAME_COUNTS ON NameID = FK_NameID
JOIN YEAR_GENDER_TOTALS ON YearGenderTotalID = FK_YearGenderTotalID
WHERE Year = {$safe_year}
AND Gender = '{$safe_gender}'
ORDER BY Rank
LIMIT 0, {$safe_count};
QUERY;
        $results = $db->query($query);
        $recs = $results->fetch_all(MYSQLI_NUM);
        //          $name, $gender, $year, $rank, $count, $total, $metaphone
        foreach ($recs as $rec) {
            $name_popularity_rec = new NamePopularityRecord($rec[YearSet::NAME_FIELD], $rec[YearSet::GENDER_FIELD], $rec[YearSet::YEAR_FIELD], $rec[YearSet::RANK_FIELD], $rec[YearSet::COUNT_FIELD], $rec[YearSet::TOTAL_FIELD], $rec[YearSet::METAPHONE_FIELD]);
            $this->mRecords[] = $name_popularity_rec;
        }
    }
Example #7
0
 public function importKeywords()
 {
     $db = ConnectionManager::getDataSource('default');
     $mysqli = new mysqli($db->config['host'], $db->config['login'], $db->config['password'], $db->config['database']);
     $sql = array('links', 'links_keywords');
     foreach (glob('/home/kiang/public_html/news/cache/output/*.json') as $jsonFile) {
         $json = json_decode(file_get_contents($jsonFile), true);
         $newLinkId = String::uuid();
         $json['title'] = $mysqli->real_escape_string(trim($json['title']));
         $json['url'] = $mysqli->real_escape_string($json['url']);
         $json['created'] = date('Y-m-d H:i:s', $json['created_at']);
         $sql['links'][] = "('{$newLinkId}', '{$json['title']}', '{$json['url']}', '{$json['created']}')";
         foreach ($json['keywords'] as $keywordId => $summary) {
             $lkId = String::uuid();
             $summary = $mysqli->real_escape_string(trim($summary));
             $sql['links_keywords'][] = "('{$lkId}', '{$newLinkId}', '{$keywordId}', '{$summary}')";
         }
         unlink($jsonFile);
     }
     if (!empty($sql['links'])) {
         $linksSql = 'INSERT INTO links VALUES ' . implode(',', $sql['links']) . ";\n";
         $lkSql = 'INSERT INTO links_keywords VALUES ' . implode(',', $sql['links_keywords']) . ';';
         file_put_contents(TMP . 'keywords.sql', $linksSql . $lkSql);
     }
 }
 public static function login($data)
 {
     $config = new Config();
     $mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
     if ($mysqli->connect_errno) {
         print json_encode(array('success' => false, 'status' => 400, 'msg' => 'Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error));
         return;
     } else {
         $username = $mysqli->real_escape_string($data['username']);
         $password = $mysqli->real_escape_string($data['password']);
         $query1 = "SELECT * FROM judges WHERE judgeuname = '{$username}' AND judgepword='{$password}'";
         $result = $mysqli->query($query1);
         if ($result) {
             if ($row = $result->fetch_assoc()) {
                 /*** set the session user_id variable ***/
                 $_SESSION['user'] = $row;
                 /*** set a form token ***/
                 $form_token = md5(uniqid('auth', true));
                 /*** set the session form token ***/
                 $_SESSION['auth_token'] = $form_token;
                 /*** tell the user we are logged in ***/
                 print json_encode(array('success' => true, 'status' => 200, 'form_token' => $form_token, 'childs' => $row));
             } else {
                 $message = 'Login Failed';
                 print json_encode(array('success' => false, 'status' => 200, 'msg' => $message));
             }
         } else {
             $message = 'Error with SQL' . $query1;
             print json_encode(array('success' => false, 'status' => 400, 'msg' => $message));
         }
     }
 }
Example #9
0
    function __construct($name, $gender, $metaphone)
    {
        $this->mRecords = [];
        $db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
        $safe_name = $db->real_escape_string($name);
        $safe_gender = $db->real_escape_string($gender);
        $query = <<<QUERY
SELECT Year, IFNULL((
    SELECT  NameCount
    FROM    NAME_COUNTS
    JOIN    NAMES ON NameID = FK_NameID
    WHERE   Name = '{$safe_name}'
    AND     YearGenderTotalID = FK_YearGenderTotalID
), 0) AS NameCount,
          Total
FROM \tyear_gender_totals
WHERE\tGender = '{$safe_gender}'
ORDER BY\tYear;
QUERY;
        $results = $db->query($query);
        $recs = $results->fetch_all(MYSQLI_NUM);
        //          $name, $gender, $year, $rank, $count, $total, $metaphone
        foreach ($recs as $rec) {
            $name_popularity_rec = new NamePopularityRecord($name, $gender, $rec[NameSet::YEAR_FIELD], 0, $rec[NameSet::COUNT_FIELD], $rec[NameSet::TOTAL_FIELD], $metaphone);
            $this->mRecords[] = $name_popularity_rec;
        }
    }
Example #10
0
function saveDataToDatabase()
{
    date_default_timezone_set("Asia/Tokyo");
    //set timezone to Tokyo
    $date = date("Y-m-d H:i:s");
    $servername = "domremy.xsrv.jp";
    $username = "******";
    $password = "******";
    $dbname = "domremy_product";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    $ProductName = $conn->real_escape_string($_POST["product"]);
    $PepperText = $conn->real_escape_string($_POST["pepperText"]);
    $Text = $conn->real_escape_string($_POST["detail"]);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "INSERT INTO product_tb (productName, productDetailText, productPepperText, productRecodeDate, productValidity)\n                VALUES ('{$ProductName}', '{$Text}','{$PepperText}','{$date}','1')";
    if ($conn->query($sql) === TRUE) {
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = strtolower(end($temp));
        $id = $conn->insert_id;
        $filename = $id . "." . $extension;
        $sql = "UPDATE product_tb SET productFileName ='{$filename}' WHERE productId='{$id}'";
        $conn->query($sql);
        saveImageToServer($filename);
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
}
Example #11
0
 /**
  * @inheritDoc
  */
 public function escapeValues(array $values)
 {
     $escaped = [];
     foreach ($values as $value) {
         $escaped[] = $this->conn->real_escape_string($value);
     }
     return $escaped;
 }
 /**
  * Auto-generate a FIND_IN_SET() statement
  *
  * @param string  $strKey     The field name
  * @param mixed   $varSet     The set to find the key in
  * @param boolean $blnIsField If true, the set will not be quoted
  *
  * @return string The FIND_IN_SET() statement
  */
 protected function find_in_set($strKey, $varSet, $blnIsField = false)
 {
     if ($blnIsField) {
         return "FIND_IN_SET(" . $strKey . ", " . $varSet . ")";
     } else {
         return "FIND_IN_SET(" . $strKey . ", '" . $this->resConnection->real_escape_string($varSet) . "')";
     }
 }
Example #13
0
function addMOProperty($unifiedName, $client)
{
    $mysqli = new mysqli(HOSTNAME, USERNAME, PASSWD, DATABASE);
    if ($mysqli->connect_errno) {
        die("error: " . $mysqli->connect_error);
    }
    $localTable = "MOSpacePeople";
    $parser = new HumanNameParser_Parser($unifiedName);
    $last = $parser->getLast();
    $first = $parser->getFirst();
    //@Debug
    //echo "Checking ".$last.", ".$first.".....";
    $q = "SELECT * from " . $localTable . " where firstname='" . $mysqli->real_escape_string($first) . "' and lastname='" . $mysqli->real_escape_string($last) . "'";
    $fromMU = 0;
    $isProfessor = 0;
    if ($result = $mysqli->query($q)) {
        if ($result->num_rows == 1) {
            //@Debug
            //echo "found in local database.....";
            $fromMU = 1;
            if ($resAssocArray = $result->fetch_assoc()) {
                if (isset($resAssocArray['Title'])) {
                    $isProfessor = findIfProfessor($resAssocArray['Title']) == 1 ? 1 : 0;
                    //@Debug
                    //if($isProfessor == 1) echo "is a prof\n"; else echo "NOT a prof\n";
                } else {
                    $isProfessor = 0;
                    //@Debu
                    //echo "NOT a prof\n";
                }
            } else {
                die("fetch result from MOSpacePeople failed");
            }
        } else {
            $peopleFinderURL = "https://webservices.doit.missouri.edu/peoplefinderWS/peoplefinderws.asmx/PeopleFinderXml?firstName=" . urlencode($first) . "&lastname=" . urlencode($last) . "&department=&phoneno=&email=";
            $url_parser = new URLParser($peopleFinderURL);
            $retArr = $url_parser->XMLToArray();
            if (intval($retArr['@attributes']['found']) == 1) {
                //@Debug
                //echo "found in Peoplefinder...";
                $fromMU = 1;
                $title = array_key_exists("Title", $retArr['Person']) && !empty($retArr['Person']['Title']) ? $retArr['Person']['Title'] : "";
                $isProfessor = findIfProfessor($title) == 1 ? 1 : 0;
                //@Debug
                //if($isProfessor == 1) echo "is a prof\n"; else echo "NOT a prof\n";
            } else {
                $isProfessor = 0;
                //@Debug
                //echo "NOT a prof\n";
            }
        }
    } else {
        die("query: " . $q . "\nFailed");
    }
    $q_str = "match (u:Person {name: \"" . $unifiedName . "\"}) set u.fromMU = " . $fromMU . ", u.isProfessor = " . $isProfessor;
    $query = new Query($client, $q_str);
    $client->executeCypherQuery($query);
}
 /**
  * @access public
  * @param mixed $data
  * @return mixed $data
  */
 public function escape($data)
 {
     if (!is_array($data)) {
         $data = $this->link->real_escape_string($data);
     } else {
         $data = array_map(array($this, 'escape'), $data);
     }
     return $data;
 }
Example #15
0
 /**
  * @param $row
  * @param $configuration
  * @return mixed
  */
 public function saveRow($row, $configuration)
 {
     array_walk($row, function (&$item) {
         $item = '"' . $this->link->real_escape_string($item) . '"';
     });
     $query = sprintf('INSERT INTO %s (%s) VALUES (%s)', $configuration['table'], implode(', ', array_keys($row)), implode(', ', $row));
     $this->link->query($query);
     return $this->link->insert_id;
 }
Example #16
0
function login($user, $pass)
{
    if (file_exists("config.php")) {
        require "config.php";
    } else {
        require "../config.php";
    }
    $loginuser = stripslashes($user);
    $loginpass = stripslashes($pass);
    if (!isset($loginuser) || !isset($loginpass)) {
        $status = "3";
    } elseif (empty($loginuser) || empty($loginpass)) {
        $status = "3";
    } else {
        $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        $loginuser = $mysqli->real_escape_string($user);
        $loginpass = $mysqli->real_escape_string($pass);
        $sql = $mysqli->query("SELECT timeout,loglogins,servername,fetchcsp FROM settings WHERE id='1'");
        $sline = $sql->fetch_array();
        $sql = $mysqli->query("SELECT id,enabled,admlvl,ugroup FROM admins WHERE user='******' AND pass='******'");
        $rowcheck = $sql->num_rows;
        $line = $sql->fetch_array();
        if ($rowcheck == 1) {
            if ($line["enabled"] == "0") {
                if ($sline["loglogins"] == "1" || $sline["loglogins"] == "2") {
                    $mysqli->query("INSERT INTO log_login (status,ip,user,pass) VALUES ('2','" . $_SERVER["REMOTE_ADDR"] . "','" . $loginuser . "','')");
                }
                mysqli_close($mysqli);
                $status = "2";
            } else {
                if ($sline["loglogins"] == "1") {
                    $mysqli->query("INSERT INTO log_login (status,ip,user,pass) VALUES ('0','" . $_SERVER["REMOTE_ADDR"] . "','" . $loginuser . "','')");
                }
                mysqli_close($mysqli);
                @session_start();
                session_regenerate_id(true);
                $_SESSION[$secretkey . "sessid"] = session_id();
                $_SESSION[$secretkey . "user"] = $loginuser;
                $_SESSION[$secretkey . "userid"] = $line["id"];
                $_SESSION[$secretkey . "userlvl"] = $line["admlvl"];
                $_SESSION[$secretkey . "usergrp"] = $line["ugroup"];
                $_SESSION[$secretkey . "timeout"] = $sline["timeout"];
                $_SESSION[$secretkey . "servername"] = $sline["servername"];
                $_SESSION[$secretkey . "fetchcsp"] = $sline["fetchcsp"];
                $status = "0";
            }
        } else {
            if ($sline["loglogins"] == "1" || $sline["loglogins"] == "2") {
                $mysqli->query("INSERT INTO log_login (status,ip,user,pass) VALUES ('1','" . $_SERVER["REMOTE_ADDR"] . "','" . $loginuser . "','" . $loginpass . "')");
            }
            mysqli_close($mysqli);
            $status = "1";
        }
    }
    return $status;
}
Example #17
0
 public static function create($aid, $cid, $duedate, $title, $description)
 {
     $mysqli = new mysqli("classroom.cs.unc.edu", "smolster", "Moleboy4=Moleboy4", "smolsterdb");
     $result = $mysqli->query("INSERT INTO Assignments (cid, duedate, title, description) VALUES ('" . intval($cid) . "', '" . $mysqli->real_escape_string($duedate) . "', '" . $mysqli->real_escape_string($title) . "', '" . $mysqli->real_escape_string($description) . "')");
     if ($result) {
         $aid = $mysqli->insert_id;
         return new Assignment($aid, $cid, $duedate, $title, $description);
     }
     return null;
 }
Example #18
0
 /**
  * (non-PHPdoc)
  * @see Phine/Framework/Database/Interfaces/IDatabaseEscaper#EscapeValue($identifier)
  */
 function EscapeValue($value)
 {
     if ($value === null) {
         return 'NULL';
     }
     if ($value instanceof Date) {
         $value = $value->ToString('Y-m-d H:i:s');
     }
     return "'" . $this->db->real_escape_string($value) . "'";
 }
Example #19
0
 /**
  * @param \pocketmine\Player|string $player
  * @param float $defaultMoney
  * @return bool
  */
 public function createAccount($player, $defaultMoney = 1000)
 {
     if ($player instanceof Player) {
         $player = $player->getName();
     }
     $player = strtolower($player);
     if (!$this->accountExists($player)) {
         $this->db->query("INSERT INTO user_money (username, money) VALUES ('" . $this->db->real_escape_string($player) . "', {$defaultMoney});");
     }
     return false;
 }
Example #20
0
 public function quote($input, $format = self::QUOTE_MIXED)
 {
     $escaped = $this->connection->real_escape_string($input);
     if (self::QUOTE_SQL == $format) {
         return "`{$escaped}`";
     }
     if (is_numeric($escaped)) {
         return $escaped;
     } else {
         return "\"{$escaped}\"";
     }
 }
Example #21
0
 public function quoteSmart($value)
 {
     // если magic_quotes_gpc включена - используем stripslashes
     if (get_magic_quotes_gpc()) {
         $value = stripslashes($value);
     }
     // Если переменная - число, то экранировать её не нужно
     // если нет - то окружем её кавычками, и экранируем
     if (!is_numeric($value)) {
         $value = "'" . $this->mysqli->real_escape_string($value) . "'";
     }
     return $value;
 }
Example #22
0
 public function update(mysqli $conn, &$bookId)
 {
     parse_str($_SERVER['QUERY_STRING'], $update_vars);
     $bookId = $update_vars['id'];
     $newTitle = $conn->real_escape_string($this->getTitle());
     $newAuthor = $conn->real_escape_string($this->getAuthor());
     $newDesc = $conn->real_escape_string($this->getDesc());
     $sqlUpdate = "UPDATE books SET title=\n'.{$newTitle}.' , author = '.{$newAuthor}.' , desc = '.{$newDesc}.' WHERE id = {$bookId} ";
     $result = $conn->query($sqlUpdate);
     if ($result == false) {
         echo "Error during updating ";
     }
 }
Example #23
0
 public static function create($user_id, $group_id)
 {
     $mysqli = new mysqli("classroom.cs.unc.edu", "dbobbitt", "comp426final", "dbobbittdb");
     $sql_query = "INSERT INTO `Member` (user_id, group_id) VALUES (" . intval($mysqli->real_escape_string($user_id)) . ", " . intval($mysqli->real_escape_string($group_id)) . ")";
     $result = $mysqli->query($sql_query);
     if ($result) {
         //print("SUCCESS: " . $sql_query . "<br>");
         $id = $mysqli->insert_id;
         return new Member($id, $user_id, $group_id, date('Y-m-d'));
     }
     //print("ERROR: " . $sql_query . "<br>");
     return null;
 }
Example #24
0
 public static function create($message_id, $user_id)
 {
     $mysqli = new mysqli("classroom.cs.unc.edu", "dbobbitt", "comp426final", "dbobbittdb");
     $sql_query = "INSERT INTO `DirectedMessage` (message_id, user_id) VALUES (" . intval($mysqli->real_escape_string($message_id)) . ", " . intval($mysqli->real_escape_string($user_id)) . ")";
     $result = $mysqli->query($sql_query);
     if ($result) {
         print "SUCCESS: " . $sql_query . "<br>";
         $id = $mysqli->insert_id;
         return new DirectedMessage($id, $message_id, $user_id);
     }
     print "ERROR: " . $sql_query . "<br>";
     return null;
 }
 /**
  * Returns 'LIKE' part of a query.
  *
  * Note that mysql does not support $casesensitive = true and $accentsensitive = false.
  * More information in http://bugs.mysql.com/bug.php?id=19567.
  *
  * @param string $fieldname usually name of the table column
  * @param string $param usually bound query parameter (?, :named)
  * @param bool $casesensitive use case sensitive search
  * @param bool $accensensitive use accent sensitive search (ignored if $casesensitive is true)
  * @param bool $notlike true means "NOT LIKE"
  * @param string $escapechar escape char for '%' and '_'
  * @return string SQL code fragment
  */
 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\')
 {
     if (strpos($param, '%') !== false) {
         debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
     }
     $escapechar = $this->mysqli->real_escape_string($escapechar);
     // prevents problems with C-style escapes of enclosing '\'
     $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
     if ($casesensitive) {
         // Current MySQL versions do not support case sensitive and accent insensitive.
         return "{$fieldname} {$LIKE} {$param} COLLATE utf8_bin ESCAPE '{$escapechar}'";
     } else {
         if ($accentsensitive) {
             // Case insensitive and accent sensitive, we can force a binary comparison once all texts are using the same case.
             return "LOWER({$fieldname}) {$LIKE} LOWER({$param}) COLLATE utf8_bin ESCAPE '{$escapechar}'";
         } else {
             // Case insensitive and accent insensitive.
             $collation = '';
             if ($this->get_dbcollation() == 'utf8_bin') {
                 // Force a case insensitive comparison if using utf8_bin.
                 $collation = 'COLLATE utf8_unicode_ci';
             }
             return "{$fieldname} {$LIKE} {$param} {$collation} ESCAPE '{$escapechar}'";
         }
     }
 }
 /**
  * Deletes data for given session id
  *
  * @param string $id session id
  *
  * @return boolean
  */
 public function destroy($id)
 {
     $query = 'DELETE FROM `' . $this->tableName . '`';
     $query .= ' WHERE `' . $this->fieldSessionId . '`';
     $query .= ' = \'' . $this->dbAdapter->real_escape_string($id) . '\'';
     return (bool) $this->dbAdapter->query($query);
 }
Example #27
0
 /**
  * Requires a database config file or object to be loaded and the mysqli extension for PHP to be installed</br>
  *
  * Escape a String
  * @example
  * <code>
  *   $string = "that's all folks";
  *   $string = \Rhonda\Mysql::real_escape($string);
  * </code>
  *
  * Escape an Object
  * @example
  * <code>
  *   $object = new \stdClass();
  *   $object->thing = "it's for real";
  *   $object = \Rhonda\Mysql::real_escape($object);
  * </code>
  *
  * Escape an Array
  * @example
  * <code>
  * $array = array(
  *    "ray"=>"it's escaping arrays"
  *  , "ray2"=>"escape's this one too"
  * );
  * $array = \Rhonda\Mysql::real_escape($ray);
  *
  * @return Type - Mysql escaped resource that was operated on
  *
  * @since   2015-11-20
  * @author  Deac Karns <*****@*****.**> 
  **/
 public static function real_escape($thing)
 {
     // check that a configuration object exists for DB
     try {
         $db = \Rhonda\Config::get('DB')->connections->local;
     } catch (\Exception $e) {
         echo \Rhonda\Error::handle($e);
     }
     $mysqli = new \mysqli($db->host, $db->user, $db->password, $db->database, $db->port);
     $mysqli->set_charset("utf8");
     if ($mysqli->connect_errno) {
         echo \Rhonda\Error::handle($mysqli->connect_error);
     }
     // test the thing that is coming in
     switch (gettype($thing)) {
         case 'string':
             $escaped = $mysqli->real_escape_string($thing);
             break;
         case 'object':
             $escaped = self::escape_collection($thing, $mysqli);
             break;
         case 'array':
             $escaped = self::escape_collection($thing, $mysqli);
             break;
         default:
             $escaped = $thing;
             break;
     }
     return $escaped;
 }
Example #28
0
 public function addBook(mysqli $conn)
 {
     //powtórzyc 500 razy!!!
     $newName = $conn->real_escape_string($this->getName());
     //for security of input
     $newDesc = $conn->real_escape_string($this->getDesc());
     //for security of input
     $newAuthor = $conn->real_escape_string($this->getAuthor());
     //for security of input
     $sql = "INSERT INTO Books(name, author, opis) VALUES ('" . $newName . "','" . $newAuthor . "','" . $newDesc . "')";
     $result = $conn->query($sql);
     if ($result == false) {
         echo "Błąd dodawnia do bazy danych";
     }
     return $conn->insert_id;
 }
Example #29
0
 /**
  * Dumps table to logical file.
  * @param  resource
  * @return void
  */
 public function dumpTable($handle, $table)
 {
     $res = $this->connection->query("SHOW CREATE TABLE `{$table}`");
     $row = $res->fetch_assoc();
     $res->close();
     fwrite($handle, "-- --------------------------------------------------------\n\n");
     $mode = isset($this->tables[$table]) ? $this->tables[$table] : $this->tables['*'];
     $view = isset($row['Create View']);
     if ($mode & self::DROP) {
         fwrite($handle, 'DROP ' . ($view ? 'VIEW' : 'TABLE') . " IF EXISTS `{$table}`;\n\n");
     }
     if ($mode & self::CREATE) {
         fwrite($handle, $row[$view ? 'Create View' : 'Create Table'] . ";\n\n");
     }
     if ($view || !($mode & self::DATA)) {
         return;
     }
     $numeric = array();
     $res = $this->connection->query("SHOW COLUMNS FROM `{$table}`");
     $cols = array();
     while ($row = $res->fetch_assoc()) {
         $col = $row['Field'];
         $cols[] = '`' . str_replace('`', '``', $col) . '`';
         $numeric[$col] = (bool) preg_match('#^[^(]*(BYTE|COUNTER|SERIAL|INT|LONG|CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER)#i', $row['Type']);
     }
     $cols = '(' . implode(', ', $cols) . ')';
     $res->close();
     $size = 0;
     $res = $this->connection->query("SELECT * FROM `{$table}`", MYSQLI_USE_RESULT);
     while ($row = $res->fetch_assoc()) {
         $s = '(';
         foreach ($row as $key => $value) {
             if ($value === NULL) {
                 $s .= "NULL,\t";
             } elseif ($numeric[$key]) {
                 $s .= $value . ",\t";
             } else {
                 $s .= "'" . $this->connection->real_escape_string($value) . "',\t";
             }
         }
         if ($size == 0) {
             $s = "INSERT INTO `{$table}` {$cols} VALUES\n{$s}";
         } else {
             $s = ",\n{$s}";
         }
         $len = strlen($s) - 1;
         $s[$len - 1] = ')';
         fwrite($handle, $s, $len);
         $size += $len;
         if ($size > self::MAX_SQL_SIZE) {
             fwrite($handle, ";\n");
             $size = 0;
         }
     }
     $res->close();
     if ($size) {
         fwrite($handle, ";\n");
     }
     fwrite($handle, "\n\n");
 }
Example #30
0
 public function escape($string)
 {
     if (null === $this->mysqli) {
         $this->connect();
     }
     return $this->mysqli->real_escape_string((string) $string);
 }