Example #1
0
 /**
  * Clear Magento instance: remove all tables in DB and use dump to load new ones, clear Magento cache
  *
  * @throws \Exception
  */
 public function clearInstance()
 {
     $magentoBaseDir = dirname(dirname(dirname(MTF_BP)));
     $config = simplexml_load_file($magentoBaseDir . '/app/etc/local.xml');
     $host = (string) $config->connection->host;
     $user = (string) $config->connection->username;
     $password = (string) $config->connection->password;
     $database = (string) $config->connection->dbName;
     $fileName = MTF_BP . '/' . $database . '.sql';
     if (!file_exists($fileName)) {
         echo 'Database dump was not found by path: ' . $fileName;
         return;
     }
     // Drop all tables in database
     $mysqli = new \mysqli($host, $user, $password, $database);
     $mysqli->query('SET foreign_key_checks = 0');
     if ($result = $mysqli->query("SHOW TABLES")) {
         while ($row = $result->fetch_row()) {
             $mysqli->query('DROP TABLE ' . $row[0]);
         }
     }
     $mysqli->query('SET foreign_key_checks = 1');
     $mysqli->close();
     // Load database dump
     exec("mysql -u{$user} -p{$password} {$database} < {$fileName}", $output, $result);
     if ($result) {
         throw new \Exception('Database dump loading has been failed: ' . $output);
     }
     // Clear cache
     exec("rm -rf {$magentoBaseDir}/var/*", $output, $result);
     if ($result) {
         throw new \Exception('Cleaning Magento cache has been failed: ' . $output);
     }
 }
Example #2
0
 function connect($name, $path = false)
 {
     $this->name = $name;
     global $cfg;
     $link = new mysqli($cfg->mysqli_host, $cfg->mysqli_username, $cfg->mysqli_password);
     // Make sure database exists
     $res = $link->query("SHOW DATABASES");
     while ($row = $res->fetch_row()) {
         if ($row[0] == $name) {
             $do = true;
         }
     }
     if (!isset($do)) {
         $do = false;
     }
     if (!$do) {
         $link->query("CREATE DATABASE {$name}");
     }
     $link->select_db($name);
     // check connection
     if (mysqli_connect_errno()) {
         printf("Connect failed: %s\n", mysqli_connect_error());
         exit;
     }
     $this->link = $link;
     return $link;
 }
Example #3
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);
        }
    }
}
Example #4
0
 /**
  * Query database
  *
  * @param   string        $sql          SQL Query
  * @param   array|string  $replacement  Replacement
  * @return  mixed
  */
 public function query()
 {
     $args = func_get_args();
     $sql = array_shift($args);
     // Menerapkan $replacement ke pernyataan $sql
     if (!empty($args)) {
         $sql = vsprintf($sql, $args);
     }
     try {
         // Return 'false' kalo belum ada koneksi
         if (!$this->_db) {
             $this->connect();
         }
         $this->_sql = $sql;
         // Eksekusi SQL Query
         if ($results = $this->_db->query($sql)) {
             if (is_bool($results)) {
                 return $results;
             }
             $this->_results = $results;
             $this->_num_rows = $this->_results->num_rows;
             return $this;
         } else {
             App::error($this->_db->error . '<br>' . $this->_sql);
         }
     } catch (Exception $e) {
         set_alert('error', $e->getMessage());
         return false;
     }
 }
Example #5
0
function datapages()
{
    if ($_SESSION['userinfo']['status'] === 1) {
        $conn = new mysqli('localhost', 'root', '12345password12345', 'main');
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $num_rows_res = $conn->query("SELECT count(*) FROM mlib;");
        $num_rows = mysqli_fetch_array($num_rows_res, MYSQLI_NUM)[0];
        for ($i = 1; $i <= $num_rows; $i++) {
            $pages_sql = "Select * FROM mlib WHERE c_id=" . $i . ";";
            $pages_res = $conn->query($pages_sql);
            $pages[$i] = mysqli_fetch_object($pages_res);
        }
        $conn->close();
    } else {
        $conn = new mysqli('localhost', 'root', '12345password12345', 'main');
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $num_rows_res = $conn->query("SELECT count(*) FROM mlib WHERE viewers='all';");
        $num_rows = mysqli_fetch_array($num_rows_res, MYSQLI_NUM)[0];
        for ($i = 1; $i <= $num_rows; $i++) {
            $pages_sql = "Select * FROM mlib WHERE c_id=" . $i . " AND viewers='all';";
            $pages_res = $conn->query($pages_sql);
            $pages[$i] = mysqli_fetch_object($pages_res);
        }
        $conn->close();
    }
    return $pages;
}
Example #6
0
 public function execute($sql)
 {
     if ($result = $this->connection->query($sql)) {
         return true || $result->close();
     }
     throw new Exception($this->connection->error);
 }
 public function onPreQuery(\mysqli $db)
 {
     $result = $db->query("SELECT tid, config, (SELECT type FROM tjrequests WHERE team=teams.tid AND user={$this->uid}) AS type FROM teams WHERE name={$this->esc($this->teamName)}");
     $checkFirst = $result->fetch_assoc();
     $result->close();
     if (!is_array($checkFirst)) {
         throw new \RuntimeException(Phrases::CMD_TEAM_ERR_NO_SUCH_TEAM);
     }
     $this->tid = (int) $checkFirst["tid"];
     $this->type = (int) $checkFirst["type"];
     $config = (int) $checkFirst["config"];
     $result->close();
     if ($config & Settings::TEAM_CONFIG_OPEN) {
         $this->type = self::DIRECT_JOIN;
         throw new \RuntimeException(Phrases::CMD_TEAM_JOIN_DIRECTLY_JOINED);
     }
     if ($this->type === self::REQUEST_FROM_USER) {
         throw new \RuntimeException(Phrases::CMD_TEAM_JOIN_ALREADY_REQUESTED);
     } elseif ($this->type === self::REQUEST_FROM_TEAM or $this->type === self::DIRECT_JOIN) {
         $query = $db->query("SELECT (SELECT COUNT(*) FROM users WHERE tid=teams.tid) AS members,slots FROM teams WHERE tid={$this->tid}");
         $row = $query->fetch_assoc();
         $query->close();
         $members = (int) $row["members"];
         $slots = (int) $row["slots"];
         if ($members >= $slots) {
             throw new \RuntimeException(Phrases::CMD_TEAM_ERR_FULL);
         }
     }
 }
Example #8
0
 /**
  * 执行一条sql语句
  *
  * @param string $sql sql语句
  * @param bool $cache 是否缓存
  * @return ResultSet
  */
 public function query($sql, $cache = false)
 {
     // 读缓存
     if ($cache) {
         $cache = new Cache();
         $rtn = $cache->get($sql);
         if ($rtn) {
             return unserialize($rtn);
         }
     }
     // 读数据库
     switch (DBManager::workingMode()) {
         case DBManager::MODE_PDO:
             $rs = $this->_link->query($sql);
             break;
         case DBManager::MODE_SQLI:
             $rs = $this->_link->query($sql);
             break;
         case DBManager::MODE_SQL:
             $rs = mysql_query($sql, $this->_link);
             break;
         default:
             $rs = false;
             break;
     }
     $rtn = new ResultSet($rs, $sql, $cache);
     return $rtn;
 }
function IMPORT_TABLES($host, $user, $pass, $dbname, $sql_file)
{
    if (!file_exists($sql_file)) {
        die('Input the SQL filename correctly! <button onclick="window.history.back();">Click Back</button>');
    }
    $allLines = file($sql_file);
    $mysqli = new mysqli($host, $user, $pass, $dbname);
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $zzzzzz = $mysqli->query('SET foreign_key_checks = 0');
    preg_match_all("/\nCREATE TABLE(.*?)\\`(.*?)\\`/si", "\n" . file_get_contents($sql_file), $target_tables);
    foreach ($target_tables[2] as $table) {
        $mysqli->query('DROP TABLE IF EXISTS ' . $table);
    }
    $zzzzzz = $mysqli->query('SET foreign_key_checks = 1');
    $mysqli->query("SET NAMES 'utf8'");
    $templine = '';
    // Temporary variable, used to store current query
    foreach ($allLines as $line) {
        // Loop through each line
        if (substr($line, 0, 2) != '--' && $line != '') {
            $templine .= $line;
            // (if it is not a comment..) Add this line to the current segment
            if (substr(trim($line), -1, 1) == ';') {
                // If it has a semicolon at the end, it's the end of the query
                $mysqli->query($templine) or print 'Error performing query \'<strong>' . $templine . '\': ' . $mysqli->error . '<br /><br />';
                $templine = '';
                // Reset temp variable to empty
            }
        }
    }
    echo 'Importing finished. Now, Delete the import file.';
}
Example #10
0
function getRoomName($room_id)
{
    $room_name = "";
    $conn = new mysqli("localhost", "mrbs", "mrbs-password", 'mrbs');
    if ($conn->connect_error) {
        die("connection failed.<>" . $conn->connect_error);
    }
    // echo "connected :) ";
    $query = "select room_name from mrbs_room where id = {$room_id}";
    // print $query;
    if ($conn->query($query) == True) {
        // echo "here1";
        $res = $conn->query($query);
        // print ($res[1]);
        foreach ($res as $room) {
            // print ($room["room_name"]);
            $room_name = $room["room_name"];
            // print $room_name;
        }
        // print "room found";
        // print $room_name;
        return $room_name;
    } else {
        return "Error in room_id: " . $room_id[0];
    }
    // return $room_name;
}
function enterdata($fdata, $clientid, $period, $py, $lieu, $nav, $edt, $eau, $comptetype)
{
    $totalfcp = 0;
    for ($counter = 0; $counter < count($fdata); $counter += 1) {
        $detail = explode("#", $fdata[$counter]);
        $totalfcp += $detail[1] * $detail[2];
    }
    $totalfcp += $edt;
    $totalfcp += $eau;
    $totaleuro = $totalfcp / 120;
    $totaleuro = round($totaleuro, 2);
    $today = date("Y-m-d");
    $mysqli = new mysqli(DBSERVER, DBUSER, DBPWD, DB);
    $query = "SELECT `chrono` FROM `" . DB . "`.`chrono` ORDER BY `id` DESC LIMIT 1;";
    $result = $mysqli->query($query);
    $row = $result->fetch_array(MYSQLI_ASSOC);
    $chrono = $row["chrono"] + 1;
    $query = "INSERT INTO `" . DB . "`.`chrono` (`chrono`) VALUES ('" . $chrono . "')";
    $mysqli->query($query);
    $query = "INSERT INTO `" . DB . "`.`factures_amarrage` (`idfacture`, `idclient`, `type_client`," . " `datefacture`, `communeid`, `montantfcp`, `montanteuro`, `restearegler`,`obs`,`PY`,`lieu`,`navire`,`edt`,`eau`)" . " VALUES (NULL, '" . $clientid . "', '" . $comptetype . "', '" . $today . "', '" . $chrono . "', '" . $totalfcp . "', '" . $totaleuro . "', '" . $totalfcp . "', '" . $period . "', '" . $py . "', '" . $lieu . "', '" . $nav . "', '" . $edt . "', '" . $eau . "')";
    //return $query;
    $mysqli->query($query);
    $lastid = $mysqli->insert_id;
    //use it to insert the details.
    // insert details now
    for ($counter = 0; $counter < count($fdata); $counter += 1) {
        $detail = explode("#", $fdata[$counter]);
        $query = "INSERT INTO `" . DB . "`.`factures_amarrage_details` (`iddetail`, `idfacture`," . " `idtarif`, `quant`)" . " VALUES (NULL, '" . $lastid . "', '" . $detail[0] . "', '" . $detail[1] . "')";
        $mysqli->query($query);
    }
    $mysqli->close();
    return $lastid;
}
 public function GetTop3()
 {
     global $whichUser;
     $myDBConnector = new DBConnector();
     $dbARY = $myDBConnector->infos();
     $connection = new mysqli($dbARY[0], $dbARY[1], $dbARY[2], $dbARY[3]);
     if ($connection->connect_error) {
         return false;
     } else {
         $connection->set_charset("utf8");
         $ress0 = $connection->query("SELECT * FROM users WHERE userName = '{$whichUser}'");
         if ($ress0->num_rows == 0) {
             echo "<script type=\"text/javascript\"> window.location='oops.php'; </script>";
         }
         $query = "SELECT * FROM `threads` WHERE threadWriter='{$whichUser}' ORDER BY `threadPoint` DESC LIMIT 3 ";
         $results = $connection->query($query);
         if ($results->num_rows < 3) {
             return false;
         } else {
             $returnAry = array();
             while ($curResult = $results->fetch_assoc()) {
                 $returnAry[] = $curResult["threadPicture"];
                 $returnAry[] = $curResult["threadName"];
                 $returnAry[] = $curResult["threadID"];
             }
             return $returnAry;
         }
     }
 }
Example #13
0
function CreateGroupParticipations(mysqli $objAcsDatabase, Group $objGroup, GroupRole $objRole, $intAcsGroupId, $intAcsReserveId)
{
    print "Adding for Group: " . $objGroup->Name . "\r\n      ";
    if ($intAcsReserveId) {
        $objResult = $objAcsDatabase->query(sprintf('select * from awgrrost where groupid=%s AND reserveid1=%s', $intAcsGroupId, $intAcsReserveId));
    } else {
        $objResult = $objAcsDatabase->query(sprintf('select * from awgrrost where groupid=%s', $intAcsGroupId));
    }
    while ($objRow = $objResult->fetch_array()) {
        $objAttributeValueArray = AttributeValue::QueryArray(QQ::AndCondition(QQ::Equal(QQN::AttributeValue()->AttributeId, 2), QQ::Equal(QQN::AttributeValue()->TextValue, $objRow['indvid'])));
        if (count($objAttributeValueArray) != 1) {
            printf("Issue with awgrrost.pkid of %s - IndvId %s for Group %s - AVCount of %s\r\n", $objRow['pkid'], $objRow['indvid'], $objGroup->Name, count($objAttributeValueArray));
        } else {
            $objPerson = $objAttributeValueArray[0]->Person;
            $dttStartDate = new QDateTime($objRow['dateadded']);
            if ($objRow['dateremoved']) {
                $dttEndDate = new QDateTime($objRow['dateremoved']);
            } else {
                $dttEndDate = null;
            }
            $objGroup->AddPerson($objPerson, $objRole->Id, $dttStartDate, $dttEndDate);
            print "*";
        }
    }
    print "\r\n      Done.\r\n\r\n";
}
Example #14
0
 /**
  * @param string $text
  * @param string $author
  * @throws DbException
  */
 public function addMessage($text, $author)
 {
     $result = $this->mysqli->query("INSERT INTO `test`(`text`,`author`) VALUES ('" . $text . "', '" . $author . "')");
     if (!$result) {
         throw new DbException('Не удалось добавить сообщение');
     }
 }
Example #15
0
 public static function detail($eventid)
 {
     $config = new Config();
     $mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
     if ($mysqli->connect_errno) {
         return print json_encode(array('success' => false, 'status' => 400, 'msg' => 'Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error));
     } else {
         if ($eventid == 'all') {
             $query1 = "select a.*,b.* from criteria a right join events b on a.eventid = b.eventid";
             $result1 = $mysqli->query($query1);
             $data = array();
             while ($row = $result1->fetch_array(MYSQLI_ASSOC)) {
                 array_push($data, $row);
             }
             print json_encode(array('success' => true, 'status' => 200, 'childs' => $data), JSON_PRETTY_PRINT);
         } else {
             $query1 = "select a.*,b.* from criteria a right join events b on a.eventid = b.eventid and a.eventid = {$eventid}";
             $result1 = $mysqli->query($query1);
             $data = array();
             while ($row = $result1->fetch_array(MYSQLI_ASSOC)) {
                 array_push($data, $row);
             }
             print json_encode(array('success' => true, 'status' => 200, 'childs' => $data), JSON_PRETTY_PRINT);
         }
     }
 }
Example #16
0
    function display_res($i)
    {
        //$con = new mysqli("localhost","root","","hotels");
        $con = new mysqli("server29.000webhost.com", "a7914922_root", "1234asdf", "a7914922_hotels");
        $arr = array('chinese', 'mexican', 'south', 'cafe', 'italian', 'seafood');
        if ($i == 0) {
            $res = $con->query("select * from hotel_1");
        } else {
            $i--;
            $res = $con->query("select * from hotel_1 where speciality='{$arr[$i]}'");
        }
        echo "<br>";
        $row = $res->fetch_assoc();
        while ($row) {
            ?>
<br/><div><a href="<?php 
            echo $row['onclick'];
            ?>
"><img src="<?php 
            echo $row['image'];
            ?>
" style="width:500px;height:300px;"></a><?php 
            echo "<br><font size=6>" . $row['name'] . "</font><br>Location:" . $row['area'] . "<br>Speciality:" . $row['speciality'] . "<br>Rating:" . $row['rating'];
            ?>
</div>
<?php 
            $row = $res->fetch_assoc();
        }
    }
Example #17
0
 public function Ymysqli($url)
 {
     $url = parse_url($url);
     // Check if mysqli extension support is present in PHP
     if (!class_exists('mysqli')) {
         die('Unable to use the mysqli extension because the mysqli extension for PHP is not installed. Check your <code>php.ini</code> to see how you can enable it.');
     }
     // Decode url-encoded information in the db connection string
     $url['user'] = urldecode($url['user']);
     // Test if database url has a password.
     $url['pass'] = isset($url['pass']) ? urldecode($url['pass']) : '';
     $url['host'] = urldecode($url['host']);
     $url['path'] = urldecode($url['path']);
     // Allow for non-standard MySQL port.
     if (isset($url['port'])) {
         $url['port'] = $url['port'];
     } else {
         $url['port'] = 3306;
     }
     @($connection = new mysqli($url['host'], $url['user'], $url['pass'], substr($url['path'], 1), $url['port']));
     if (mysqli_connect_errno()) {
         throw new Exception(mysqli_connect_error());
     }
     $this->database = substr($url['path'], 1);
     // Force MySQL to use the UTF-8 character set. Also set the collation, if a
     // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
     // for UTF-8.
     if (!empty($GLOBALS['db_collation'])) {
         $connection->query('SET NAMES utf8 COLLATE ' . $GLOBALS['db_collation']);
     } else {
         $connection->query('SET NAMES utf8');
     }
     $this->lnk = $connection;
 }
Example #18
0
 function display($tpl = null)
 {
     global $mainframe;
     $id = JRequest::getVar('cid', array(0), '', 'array');
     //	$boxchecked = JRequest::getVar( 'boxchecked' );
     //	echo $boxchecked;
     $uid = (int) @$id[0];
     $edit = JRequest::getVar('edit', true);
     if ($edit) {
         if ($boxchecked != 0) {
             $uid = $boxchecked;
         }
         $mysqli = new mysqli(self::GPHOST, self::GPUSER, self::GPPASS, self::GPDB);
         $query = 'SELECT * from rgpMaterials where tid = ' . $uid;
         $result = $mysqli->query($query);
         $material = $result->fetch_object();
     }
     $mysqli = new mysqli(self::GPHOST, self::GPUSER, self::GPPASS, self::GPDB);
     $query = 'SELECT tid, name from rgpMaterialCompany';
     $result = $mysqli->query($query);
     while ($obj = $result->fetch_object()) {
         $materialcompanies[] = $obj;
     }
     $query = 'SELECT tid, name from rgpMaterialType';
     $result = $mysqli->query($query);
     while ($obj = $result->fetch_object()) {
         $materialtypes[] = $obj;
     }
     $this->assignRef('materialtypes', $materialtypes);
     $this->assignRef('materialcompanies', $materialcompanies);
     $this->assignRef('material', $material);
     parent::display($tpl);
 }
Example #19
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 #20
0
function get_email_sign_up($source)
{
    require_once "includes/config.php";
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (isset($_POST['emailSubmit'])) {
        $email = htmlentities($_POST['emailBar']);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo "<p style='margin-right: auto; margin-left: auto; text-align: center; color: red'>Invalid email address!</p>";
        } else {
            $pre_sql = "SELECT email FROM email WHERE email = '{$email}';";
            $pre_result = $mysqli->query($pre_sql);
            if ($pre_result->num_rows == 1) {
                echo "<p style='margin-right: auto; margin-left: auto; text-align: center; color: red'>You have already signed up!</p>";
            } else {
                $today = date("Y-m-d");
                $sql_1 = "INSERT INTO email (email, date_added, source) \n\t\t\t\t        VALUES ('{$email}', '{$today}', '{$source}');";
                $result = $mysqli->query($sql_1);
                if (!$result) {
                    print $mysqli->error;
                    exit;
                } else {
                    //The prompt
                    echo "<p style='margin-right: auto; margin-left: auto; text-align: center; color: green'>You signed up successfully!</p>";
                }
            }
        }
    }
}
Example #21
0
function user_likes($start = 0, $end = 0)
{
    $file_prefix = 'user_likes_57613404340_';
    $link = new mysqli('localhost', 'team1', 'yb102', 'YB102_Team1');
    $link->query("SET NAMES UTF8");
    for ($segment = $start; $segment <= $end; $segment++) {
        echo $segment . '<br>';
        $file_path = $_SERVER['DOCUMENT_ROOT'] . '/_asset/data/user_likes/' . $file_prefix . sprintf('%05d', $segment) . '.csv';
        $file = @fopen($file_path, "r");
        while (!feof($file)) {
            $data_string = fgets($file);
            str_replace("\n", "", $data_string);
            $data_array = explode(',', $data_string);
            if (count($data_array) >= 2 && strpos($data_string, 'l.facebook.com') === FALSE && strpos($data_string, 'apps.facebook.com') === FALSE) {
                $fb_user_id = $data_array[0];
                $fb_fan_page_id = $data_array[count($data_array) - 1];
                $now = date('Y-m-d H:i:s', time() + 25200);
                if ($fb_user_id) {
                    $insert_sql = "INSERT INTO `fb_user_likes` (`segment`, `fb_user_id`, `fb_fan_page_id`, `create_time`, `modify_time`) VALUES ('{$segment}', '{$fb_user_id}', '{$fb_fan_page_id}', '{$now}', '{$now}')";
                    $link->query($insert_sql);
                }
            }
        }
        fclose($file);
    }
}
Example #22
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");
 }
function database($sql, $h_success, $h_fail)
{
    $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) {
        global $msg, $result;
        $msg = "User Successfully Registered";
        $result = $conn->query($sql);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        $msg = "<br>Error: " . "<br>" . $conn->error;
        $h_fail = $h_fail . "?msg=" . $msg;
        //if(isset($h_fail))
        //{
        header($h_fail);
        exit;
        //}
    }
    $conn->close();
}
function enterdata($edit)
{
    //echo "entering data";
    $nomvalue = strtoupper($_POST['txt_Nom']);
    $prenomvalue = strtoupper($_POST['txt_Prenom']);
    $prenomvalue = strtr($prenomvalue, utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    $_POST['chk_status'] = isset($_POST['chk_status']) ? 1 : 0;
    $_POST['txt_Notahiti'] == '' ? $notahiti = 'NULL' : ($notahiti = $_POST['txt_Notahiti']);
    //$status='TRUE';
    $Mysqli = new mysqli(DBSERVER, DBUSER, DBPWD, DB);
    if ($edit == 0) {
        //new insert
        $query = "INSERT INTO `" . DB . "`.`mandataires` (`mandataireid`," . " `mandataireprefix`, `mandataireRS`," . " `mandatairestatus`, `mandatairenom`," . " `mandataireprenom`, `mandataireidtresor`, `mandataireemail`, `mandatairenotahiti`, `mandataireRC`," . " `mandatairetelephone`,`mandatairetelephone2`, `mandatairefax`, `mandatairebp`," . " `mandatairecp`, `mandataireville`, `mandatairecommune`, `mandatairepays`, `aroa`, `quartier`, `mandatairerib`,`obs`)" . " VALUES (NULL, '" . $_POST['box_Prefix'] . "', '" . strtoupper($_POST['txt_RS']) . "', '" . $_POST['chk_status'] . "', '" . strtoupper($_POST['txt_Nom']) . "', '" . strtoupper($_POST['txt_Prenom']) . "', '" . $_POST['txt_IDTresor'] . "', '" . strtolower($_POST['txt_Email']) . "', '" . $notahiti . "', '" . $_POST['txt_RC'] . "', '" . $_POST['txt_Telephone'] . "', '" . $_POST['txt_Telephone2'] . "', '" . $_POST['txt_Fax'] . "', '" . $_POST['txt_BP'] . "', '" . $_POST['txt_CP'] . "', '" . addslashes(strtoupper($_POST['txt_Ville'])) . "', '" . addslashes(strtoupper($_POST['txt_Commune'])) . "', '" . strtoupper($_POST['txt_Pays']) . "', '" . addslashes(strtoupper($_POST['txt_Commune'])) . "', '" . addslashes(strtoupper($_POST['txt_Pays'])) . "', '" . $_POST['txt_RIB'] . "', '" . addslashes($_POST['txt_obs']) . "')";
        //echo $query;
        $Mysqli->query($query);
        $lastid = $Mysqli->insert_id;
        if ($Mysqli->affected_rows > 0) {
            reinitialize();
            header("Location:mandataires.php?edit={$lastid}&success=1");
        } else {
            header("Location:mandataires.php?edit={$edit}&success=0");
        }
    } else {
        //update
        $query = "UPDATE `" . DB . "`.`mandataires` SET `mandatairestatus`='" . $_POST['chk_status'] . "', `mandataireprefix`='" . $_POST['box_Prefix'] . "', `mandataireRS`='" . strtoupper($_POST['txt_RS']) . "', `mandatairenom`='" . strtoupper($_POST['txt_Nom']) . "', `mandataireprenom`='" . strtoupper($_POST['txt_Prenom']) . "', `mandataireidtresor`='" . $_POST['txt_IDTresor'] . "', `mandataireemail`='" . strtolower($_POST['txt_Email']) . "', `mandatairenotahiti`='" . $notahiti . "', `mandataireRC`='" . $_POST['txt_RC'] . "', `mandatairetelephone`='" . $_POST['txt_Telephone'] . "', `mandatairetelephone2`='" . $_POST['txt_Telephone2'] . "', `mandatairefax`='" . $_POST['txt_Fax'] . "', `mandatairebp`='" . $_POST['txt_BP'] . "', `mandatairecp`='" . $_POST['txt_CP'] . "', `mandataireville`='" . addslashes(strtoupper($_POST['txt_Ville'])) . "', `mandatairecommune`='" . addslashes(strtoupper($_POST['txt_Commune'])) . "', `mandatairepays`='" . strtoupper($_POST['txt_Pays']) . "', `aroa`='" . addslashes(strtoupper($_POST['txt_Aroa'])) . "', `quartier`='" . addslashes(strtoupper($_POST['txt_Quartier'])) . "', `mandatairerib`='" . $_POST['txt_RIB'] . "', `obs`='" . addslashes($_POST['txt_obs']) . "'" . " WHERE `mandataireid`=" . $edit;
        //echo $query;
        $Mysqli->query($query);
        if ($Mysqli->affected_rows > 0) {
            reinitialize();
            header("Location:mandataires.php?edit={$edit}&success=1");
        } else {
            header("Location:mandataires.php?edit={$edit}&success=0");
        }
    }
}
Example #25
0
 function display($tpl = null)
 {
     global $mainframe, $option;
     $db =& JFactory::getDBO();
     $search = $mainframe->getUserStateFromRequest("{$option}.search", 'search', '', 'string');
     if (strpos($search, '"') !== false) {
         $search = str_replace(array('=', '<'), '', $search);
     }
     $search = JString::strtolower($search);
     $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
     $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');
     $where = array();
     if ($search) {
         $where[] = 'LOWER(m.pn_trade) LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
     }
     $where = count($where) ? ' WHERE ' . implode(' AND ', $where) : '';
     //	if($limiter || $limit) {
     $limiter = ' LIMIT ' . $limitstart . ', ' . $limit;
     //	}
     $mysqli = new mysqli(self::GPHOST, self::GPUSER, self::GPPASS, self::GPDB);
     $query = 'SELECT pn_med_id from pn_rx_meds';
     $result = $mysqli->query($query);
     $total = $result->num_rows;
     jimport('joomla.html.pagination');
     $pagination = new JPagination($total, $limitstart, $limit);
     $query = 'SELECT m.*, comp.pn_name as companyname from pn_rx_meds m left join pn_rx_company comp on (m.pn_comp_id = comp.pn_comp_id)' . $where . ' ORDER BY m.pn_trade' . $limiter;
     $result = $mysqli->query($query);
     while ($obj = $result->fetch_object()) {
         $meds[] = $obj;
     }
     $this->assignRef('meds', $meds);
     $this->assignRef('pagination', $pagination);
     parent::display($tpl);
 }
Example #26
0
 function mysql_query($query_string)
 {
     if (!is_object($this->link)) {
         pdump(debug_backtrace());
     }
     return $this->link->query($query_string);
 }
Example #27
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 #28
0
 static function createConfig($host = 'localhost', $user, $password, $name = 'lychee', $prefix = '')
 {
     # Check dependencies
     Module::dependencies(isset($host, $user, $password, $name));
     $database = new mysqli($host, $user, $password);
     if ($database->connect_errno) {
         return 'Warning: Connection failed!';
     }
     # Check if database exists
     if (!$database->select_db($name)) {
         # Database doesn't exist
         # Check if user can create a database
         $result = $database->query('CREATE DATABASE lychee_dbcheck');
         if (!$result) {
             return 'Warning: Creation failed!';
         } else {
             $database->query('DROP DATABASE lychee_dbcheck');
         }
     }
     # Escape data
     $host = mysqli_real_escape_string($database, $host);
     $user = mysqli_real_escape_string($database, $user);
     $password = mysqli_real_escape_string($database, $password);
     $name = mysqli_real_escape_string($database, $name);
     $prefix = mysqli_real_escape_string($database, $prefix);
     # Save config.php
     $config = "<?php\n\n###\n# @name\t\t\tConfiguration\n# @author\t\tTobias Reich\n# @copyright\t2014 Tobias Reich\n###\n\nif(!defined('LYCHEE')) exit('Error: Direct access is not allowed!');\n\n# Database configuration\n\$dbHost = '{$host}'; # Host of the database\n\$dbUser = '{$user}'; # Username of the database\n\$dbPassword = '{$password}'; # Password of the database\n\$dbName = '{$name}'; # Database name\n\$dbTablePrefix = '{$prefix}'; # Table prefix\n\n?>";
     # Save file
     if (file_put_contents(LYCHEE_CONFIG_FILE, $config) === false) {
         return 'Warning: Could not create file!';
     }
     return true;
 }
function resetDatabase($dbHost, $dbName, $dbUsername, $dbPassword, $installFile, $version = null)
{
    echo "deleting all tables\r\n";
    $mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    $mysqli->query('SET foreign_key_checks = 0');
    if ($result = $mysqli->query("SHOW TABLES")) {
        while ($row = $result->fetch_array(MYSQLI_NUM)) {
            $mysqli->query('DROP TABLE IF EXISTS ' . $row[0]);
        }
    }
    $mysqli->query('SET foreign_key_checks = 1');
    echo "installing from new schema\r\n";
    playbackSQLtoDatabase($installFile, $mysqli);
    if ($mysqli->query('UPDATE user_usr SET usr_Password = "ddf23c1d9fc212aed27ea02623b51bc3a83a703a3b70a669dc81e353f3cdab22", usr_NeedPasswordChange = 0 where usr_UserName = "Admin" ')) {
        echo "Set AdminPassword.\r\n";
    }
    if ($version) {
        echo "setting version to " . $version . "\r\n";
        $qs = "INSERT INTO version_ver (ver_version, ver_update_start) VALUES ('" . $version . "', now());";
        if ($mysqli->query($qs)) {
            echo "Updated Version Table\r\n";
        }
    }
    $result = $mysqli->query("SELECT * FROM version_ver");
    $row = $result->fetch_assoc();
    echo "Version Check: " . $row['ver_version'] . "\r\n";
    $mysqli->close();
}
function register_seller()
{
    global $host, $user, $pass, $dbname;
    $db = new mysqli($host, $user, $pass, $dbname);
    $email = test_input($_POST["semail"]);
    $password = test_input($_POST["spassword"]);
    $confirm_pass = test_input($_POST["sconfirm-password"]);
    $fname = test_input($_POST["sfname"]);
    $lname = test_input($_POST["slname"]);
    $query = "SELECT * FROM SELLER WHERE SELLER.email = '" . $email . "'";
    $result = $db->query($query);
    //echo $query;
    if ($result->num_rows > 0) {
        echo '{"created": false}';
    } else {
        $count_query = "SELECT COUNT(*) FROM SELLER";
        $result2 = $db->query($count_query);
        if ($result2->num_rows > 0) {
            $row = $result2->fetch_assoc();
            $sid = $row["COUNT(*)"];
        } else {
            $sid = 0;
        }
        $insert = "INSERT INTO SELLER (sid, email, password, fname, lname) VALUES (" . $sid . ", '" . $email . "', '" . $password . "', '" . $fname . "', '" . $lname . "');";
        $db->query($insert);
        $token = 256;
        echo '{"created": true, "sid": ' . $sid . ', "fname": "' . $fname . '", "token": ' . $token . '}';
    }
}