/** * The primary method a driver needs to implement is the execute method, which takes an array of query options. * The options in the array varies, but the key type will always be supplied, which will be either SELECT, UPDATE, * INSERT, REPLACE or DELETE. * * @param array $options An array of options that were generated through use of the Query class. * @return object It is expected to return an instance of an \Queryer\Driver\DatabaseDriverResult class. * @see \Queryer\Query, \Queryer\Driver\DatabaseDriverResult */ public function execute(array $options) { $query = self::generateQuery($options); $query = DatabaseTools::replaceVariables($query, $options['variables']); $result = $this->sqlite->query($query); return new Sqlite3DriverResult($result, $this->sqlite->changes(), $this->sqlite->lastInsertRowID(), $result === false ? $this->sqlite->lastErrorCode() : null, $result === false ? $this->sqlite->lastErrorMsg() : null, $query); }
function createTransaction($user, $group_id, $purpose, $transaction_map) { $db = new SQLite3('development.sqlite3'); $stmt = $db->prepare('INSERT INTO group_transactions (user_id, group_id, purpose) VALUES (:user_id, :group_id, :purpose);'); $stmt->bindValue('user_id', $user['id'], SQLITE3_INTEGER); $stmt->bindValue('group_id', $group_id, SQLITE3_INTEGER); $stmt->bindValue('purpose', $purpose, SQLITE3_TEXT); $result = $stmt->execute(); if ($result) { $group_transaction_id = $db->lastInsertRowID(); foreach ($transaction_map as $user_id => $amount) { $stmt = $db->prepare('INSERT INTO user_transactions (user_id, other_user_id, group_transaction_id, amount VALUES (:user_id, :other_user_id, :group_transaction_id, :amount);'); $stmt->bindValue('user_id', $user['id'], SQLITE3_INTEGER); $stmt->bindValue('other_user_id', $user_id, SQLITE3_INTEGER); $stmt->bindValue('group_transaction_id', $group_transaction_id, SQLITE3_INTEGER); $stmt->bindValue('amount', $amount, SQLITE3_INTEGER); $result = $stmt->execute(); if (!$result) { return null; } } return array('user_id' => $user['id'], 'group_id' => $group_id, 'purpose' => $purpose); } else { return null; } }
function insert_album($name, $description, $location, $date) { date_default_timezone_set('Europe/London'); $created_at = date("Y-m-d H:i:s"); $sql = <<<EOF \t\t\tINSERT INTO album \t\t\t(name, description, location, date, created_at) \t\t\tVALUES \t\t\t("{$name}", "{$description}" , "{$location}", "{$date}", "{$created_at}") EOF; $result = $this->exec($sql); return SQLite3::lastInsertRowID(); }
/** * Publish a message to the queue * * @param Message $message * @return void */ public function submit(Message $message) { if ($message->getIdentifier() !== NULL) { $preparedStatement = $this->connection->prepare('SELECT rowid FROM queue WHERE msgid=:msgid'); $preparedStatement->bindValue(':msgid', $message->getIdentifier()); $result = $preparedStatement->execute(); if ($result->fetchArray(SQLITE3_NUM) !== FALSE) { return; } } $encodedMessage = $this->encodeMessage($message); $preparedStatement = $this->connection->prepare('INSERT INTO queue (msgid, payload) VALUES (:msgid, :payload);'); $preparedStatement->bindValue(':msgid', $message->getIdentifier()); $preparedStatement->bindValue(':payload', $encodedMessage); $preparedStatement->execute(); $message->setIdentifier($this->connection->lastInsertRowID()); $message->setState(Message::STATE_SUBMITTED); }
/** * @param string $query * @return array|bool|int */ public function query($query) { $this->logger->log($query); $query_type = $this->determine_query_type($query); $data = array(); if ($query_type == SQL_SELECT || $query_type == SQL_SHOW) { $SqliteResult = $this->executeQuery($query); while ($row = $SqliteResult->fetchArray(SQLITE3_ASSOC)) { $data[] = $row; } return $data; } else { $this->executeQuery($query); if ($query_type == SQL_INSERT) { return $this->sqlite3->lastInsertRowID(); } return true; } }
/** * Insert Entity * @param int $album_ID Album ID * @param String $type Nature of the file * @param String $extension Extension * @param String $description * @param String $original_name Full name of the original file, for download * @param Timestamp $taken_date Date and time of the file when created * @return int entity ID */ function insert_entity($album_ID, $type, $extension, $description, $original_name, $taken_date, $orientation) { date_default_timezone_set('Europe/London'); $created_at = date("Y-m-d H:i:s"); $updated_at = date("Y-m-d H:i:s"); $sql = <<<EOF \t\t\tINSERT INTO entity \t\t\t\t(album_ID, \t\t\t\t\ttype, \t\t\t\t\textension, \t\t\t\t\tdescription, \t\t\t\t\toriginal_file_name, \t\t\t\t\ttaken_date, \t\t\t\t\torientation, \t\t\t\t\tcreated_at, \t\t\t\t\tupdated_at \t\t\t\t) \t\t\tVALUES \t\t\t\t("{$album_ID}", \t\t\t\t\t"{$type}" , \t\t\t\t\t"{$extension}", \t\t\t\t\t"{$description}", \t\t\t\t\t"{$original_name}", \t\t\t\t\t"{$taken_date}", \t\t\t\t\t"{$orientation}", \t\t\t\t\t"{$created_at}", \t\t\t\t\t"{$updated_at}") EOF; $return = $this->exec($sql); return SQLite3::lastInsertRowID(); /*if(!$return){ echo $this->lastErrorMsg(); } else { echo "Records created successfully\n"; }*/ }
private function add_happiness() { try { // Save happiness data... // We expect: // _ location (INT) // _ happiness (INT) // _ unhappiness (INT) ensure(array_key_exists('location', $_POST), 'Location required'); ensure(array_key_exists('happiness', $_POST), 'Happiness required'); ensure(array_key_exists('unhappiness', $_POST), 'Unhappiness required'); list($location, $happiness, $unhappiness) = array(intval($_POST['location']), intval($_POST['happiness']), intval($_POST['unhappiness'])); } catch (Exception $e) { $this->bad_request($e); } // http://uk2.php.net/manual/en/sqlite3.open.php $db = new SQLite3('./happy-balls.db', SQLITE3_OPEN_READWRITE); $sql = sprintf('INSERT INTO happiness(location, happiness, unhappiness) VALUES (%d, %d, %d);', $location, $happiness, $unhappiness); $db->exec($sql); $id = $db->lastInsertRowID(); $db->close(); print "OK, id={$id}\n"; }
$user['avatar_url'] = $session['authinfo']['profile']['photo']; } $sqdb = new SQLite3('demo.sqlite'); $sqdb->exec('CREATE TABLE IF NOT EXISTS users ' . '(id INTEGER PRIMARY KEY AUTOINCREMENT, user_name STRING, first_name STRING, last_name STRING, ' . 'email STRING, profile_url STRING, avatar_url STRING, phone STRING, company STRING)'); $sqdb->exec('CREATE TABLE IF NOT EXISTS user_map (id INTEGER NOT NULL, identifier STRING, provider STRING)'); $sqdb->exec('CREATE TABLE IF NOT EXISTS user_posts (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, comment STRING)'); $identifier = $sqdb->querySingle('SELECT id FROM user_map WHERE identifier = \'' . $user['identifier'] . '\''); if (empty($identifier)) { $query = 'INSERT INTO users (user_name) VALUES (\'\')'; $insert = $sqdb->exec($query); if (!$insert) { $stat = 'fail'; $debug[] = $query; $debug[] = $sqdb->lastErrorMsg(); } else { $user['id'] = $sqdb->lastInsertRowID(); $query = 'INSERT INTO user_map (id, identifier, provider) VALUES (\'' . $user['id'] . '\',\'' . $user['identifier'] . '\',\'' . $user['provider'] . '\')'; $insert = $sqdb->exec($query); if (!$insert) { $stat = 'fail'; $debug[] = $query; $debug[] = $sqdb->lastErrorMsg(); } } } else { $user['id'] = $identifier; } if (!empty($user['id']) && $stat == 'ok') { $query = 'SELECT * FROM users WHERE id = \'' . $user['id'] . '\''; $db_user = $sqdb->querySingle($query, true); foreach ($db_user as $key => $val) {
$column12 = @$db->escapeString(trim($column12)); $column13 = @$db->escapeString(trim($column13)); $column14 = @$db->escapeString(trim($column14)); $column15 = @$db->escapeString(trim($column15)); $search = strip_tags($line); $search = mb_strtolower($search, 'utf-8'); $search = explode(' ', $search); $search = array_unique($search); $search = implode(' ', $search); $search = @$db->escapeString($search); $add = @$db->exec("INSERT INTO pages (key, ufu, column1, column2, column3, column4, column5, column6, column7, column8, column9, column10, column11, column12, column13, column14, column15, search) VALUES ('" . $line . "', '" . $ufu . "', '" . $column1 . "', '" . $column2 . "', '" . $column3 . "', '" . $column4 . "', '" . $column5 . "', '" . $column6 . "', '" . $column7 . "', '" . $column8 . "', '" . $column9 . "', '" . $column10 . "', '" . $column11 . "', '" . $column12 . "', '" . $column13 . "', '" . $column14 . "', '" . $column15 . "', '" . $search . "');"); } } $db->exec('COMMIT;'); // номер последней вставленной страницы: $lastnum = (int) $db->lastInsertRowID(); // проверяем достижение лимита количества страниц: if ($lastnum > $maxpage) { file_put_contents('log/' . $host . '.log', $maxpage); } // обновляем маркер текущей страницы if ($ufurl == '1') { $update = $db->exec("UPDATE pages SET keys='1' WHERE ufu='" . $p . "';"); } else { $update = $db->exec("UPDATE pages SET keys='1' WHERE id='" . $p . "';"); } } // конец парсинга ключевиков // парсинг контента if ($content == '' or $content == 'a:0:{}') { $badchar = array("\n", "\r", "\t", ' ', '«', '»', '"', '←', '→', ''', '–', ' ', ' ', '—', '…', ''', '→', '—', '>', '<', '{', '}', '#', '"', '—', '\'');
/** * Insert PHP make test results in SQLite database * * The following structure must be used as first array : * [status] => enum(failed, success) * [version] => string - example: 5.4.1-dev * [userEmail] => mangled * [date] => unix timestamp * [phpinfo] => string - phpinfo() output (CLI) * [buildEnvironment] => build environment * [failedTest] => array: list of failed test. Example: array('/Zend/tests/declare_001.phpt') * [expectedFailedTest] => array of expected failed test (same format as failedTest) * [succeededTest] => array of successfull tests. Provided only when parsing ci.qa results (for now) * [tests] => array testName => array ( 'output' => string("Current output of test") 'diff' => string("Diff with expected output of this test") * @param array array to insert * @param array releases we accept (so that we don't accept a report that claims to be PHP 8.1 for example) * @return boolean success or not (for the moment, error leads to a call to 'exit;' ... not good I know) */ function insertToDb_phpmaketest($array, $QA_RELEASES = array()) { if (!is_array($array)) { // impossible to fetch data. We'll record this error later ... } else { if (strtolower($array['status']) == 'failed') { $array['status'] = 0; } elseif (strtolower($array['status']) == 'success') { $array['status'] = 1; } else { die('status unknown: ' . $array['status']); } if (!is_valid_php_version($array['version'], $QA_RELEASES)) { exit('invalid version'); } $dbFile = dirname(__FILE__) . '/db/' . $array['version'] . '.sqlite'; $queriesCreate = array('failed' => 'CREATE TABLE IF NOT EXISTS failed ( `id` integer PRIMARY KEY AUTOINCREMENT, `id_report` bigint(20) NOT NULL, `test_name` varchar(128) NOT NULL, `output` STRING NOT NULL, `diff` STRING NOT NULL, `signature` binary(16) NOT NULL )', 'expectedfail' => 'CREATE TABLE IF NOT EXISTS expectedfail ( `id` integer PRIMARY KEY AUTOINCREMENT, `id_report` bigint(20) NOT NULL, `test_name` varchar(128) NOT NULL )', 'success' => 'CREATE TABLE IF NOT EXISTS success ( `id` integer PRIMARY KEY AUTOINCREMENT, `id_report` bigint(20) NOT NULL, `test_name` varchar(128) NOT NULL )', 'reports' => 'CREATE TABLE IF NOT EXISTS reports ( id integer primary key AUTOINCREMENT, date datetime NOT NULL, status smallint(1) not null, nb_failed unsigned int(10) NOT NULL, nb_expected_fail unsigned int(10) NOT NULL, success unsigned int(10) NOT NULL, build_env STRING NOT NULL, phpinfo STRING NOT NULL, user_email varchar(64) default null )'); if (!file_exists($dbFile)) { //Create DB $dbi = new SQLite3($dbFile, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); foreach ($queriesCreate as $table => $query) { $dbi->exec($query); if ($dbi->lastErrorCode() != '') { echo "ERROR when creating table " . $table . ": " . $dbi->lastErrorMsg() . "\n"; exit; } } $dbi->close(); } $dbi = new SQLite3($dbFile, SQLITE3_OPEN_READWRITE) or exit('cannot open DB to record results'); // handle tests with no success if (!isset($array['succeededTest'])) { $array['succeededTest'] = array(); } $query = "INSERT INTO `reports` (`id`, `date`, `status`, \n `nb_failed`, `nb_expected_fail`, `success`, `build_env`, `phpinfo`, user_email) VALUES (null, \n datetime(" . (int) $array['date'] . ", 'unixepoch', 'localtime'), \n " . (int) $array['status'] . ", \n " . count($array['failedTest']) . ", \n " . count($array['expectedFailedTest']) . ", \n " . count($array['succeededTest']) . ", \n ('" . $dbi->escapeString($array['buildEnvironment']) . "'), \n ('" . $dbi->escapeString($array['phpinfo']) . "'),\n " . (!$array['userEmail'] ? "NULL" : "'" . $dbi->escapeString($array['userEmail']) . "'") . "\n )"; $dbi->query($query); if ($dbi->lastErrorCode() != '') { echo "ERROR: " . $dbi->lastErrorMsg() . "\n"; exit; } $reportId = $dbi->lastInsertRowID(); foreach ($array['failedTest'] as $name) { if (substr($name, 0, 1) != '/') { $name = '/' . $name; } $test = $array['tests'][$name]; $query = "INSERT INTO `failed` \n (`id`, `id_report`, `test_name`, signature, `output`, `diff`) VALUES (null, \n '" . $reportId . "', '" . $name . "', \n X'" . md5($name . '__' . $test['diff']) . "',\n ('" . $dbi->escapeString($test['output']) . "'), ('" . $dbi->escapeString($test['diff']) . "'))"; @$dbi->query($query); if ($dbi->lastErrorCode() != '') { echo "ERROR when inserting failed test : " . $dbi->lastErrorMsg() . "\n"; exit; } } foreach ($array['expectedFailedTest'] as $name) { $query = "INSERT INTO `expectedfail` \n (`id`, `id_report`, `test_name`) VALUES (null, '" . $reportId . "', '" . $name . "')"; @$dbi->query($query); if ($dbi->lastErrorCode() != '') { echo "ERROR when inserting expected fail test : " . $dbi->lastErrorMsg() . "\n"; exit; } } foreach ($array['succeededTest'] as $name) { // sqlite files too big .. For the moment, keep only one success over time $res = $dbi->query('SELECT id, id_report FROM `success` WHERE test_name LIKE \'' . $dbi->escapeString($name) . '\''); if ($res->numColumns() > 0) { // hit ! do nothing atm } else { $query = "INSERT INTO `success` (`id`, `id_report`, `test_name`)\n VALUES (null, '" . $reportId . "', '" . $dbi->escapeString($name) . "')"; @$dbi->query($query); if ($dbi->lastErrorCode() != '') { echo "ERROR when inserting succeeded test : " . $dbi->lastErrorMsg() . "\n"; exit; } } } $dbi->close(); // remove cache if (file_exists($dbFile . '.cache')) { unlink($dbFile . '.cache'); } } return true; }
<?php $db = new SQLite3(':memory:'); echo "Creating Table\n"; var_dump($db->exec('CREATE TABLE test (time INTEGER, id STRING)')); echo "Inserting data\n"; var_dump($db->exec('INSERT INTO test (time, id) VALUES(2, 1)')); echo "Request last inserted id\n"; try { $db->lastInsertRowID(""); } catch (Exception $ex) { var_dump($ex->getMessage()); } echo "Closing database\n"; var_dump($db->close()); echo "Done";
<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="submit"> </form> <?php exit; } ?> <pre> <?php $db = new SQLite3('monitor.db'); $hashed = sha1_file($_FILES['file']['tmp_name']); $row = $db->query("SELECT id, person, result FROM image WHERE hash = '{$hashed}';")->fetchArray(); if (!$row) { $db->exec("INSERT INTO image (hash, person, result) VALUES ('{$hashed}', '<unnamed>', '<unnamed>');"); $imgid = $db->lastInsertRowID(); $imgprs = '<unnamed>'; $imgres = '<unnamed>'; move_uploaded_file($_FILES['file']['tmp_name'], "image/{$hashed}.jpg"); } else { $imgid = $row['id']; $imgprs = $row['person']; $imgres = $row['result']; } $stmt = $db->prepare("INSERT INTO record (image, person, result) VALUES (?, ?, ?);"); $stmt->bindParam(1, $imgid, SQLITE3_INTEGER); $stmt->bindParam(2, $imgprs, SQLITE3_TEXT); $stmt->bindParam(3, $imgres, SQLITE3_TEXT); if (!$stmt->execute()) { die('INSERT fail'); }
public function lastUsedID() { return $this->dbHandle->lastInsertRowID(); }
/** * Get last insert Id * * @return int */ public function getLastInsertId() { return $this->sqlite->lastInsertRowID(); }
public function insert_id() { return $this->handler->lastInsertRowID(); }
if ($method == "PUT" || $method == "DELETE") { parse_str(file_get_contents('php://input'), $request); } else { $request = $_POST; } // get id and data // !!! you need to escape data in real app, to prevent SQL injection !!! $id = @$request['id']; $rank = $request["rank"]; $year = $request["year"]; $title = $request["title"]; $votes = $request["votes"]; if ($method == "POST") { //adding new record $db->query("INSERT INTO films(rank, title, year, votes) VALUES('{$rank}', '{$title}', '{$year}', '{$votes}')"); echo '{ "id":"' . $id . '", "status":"success", "newid":"' . $db->lastInsertRowID() . '" }'; } else { if ($method == "PUT") { //updating record $db->query("UPDATE films SET rank='{$rank}', title='{$title}', year='{$year}', votes='{$votes}' WHERE id='{$id}'"); echo '{ "id":"' . $id . '", "status":"success" }'; } else { if ($method == "DELETE") { //deleting record $db->query("DELETE FROM films WHERE id='{$id}'"); echo '{ "id":"' . $id . '", "status":"success" }'; } else { echo "Not supported operation"; } } }
function submit_to_db() { if (!defined('DOKU_INC')) { define('DOKU_INC', dirname(__FILE__) . '/../../../../'); include_once DOKU_INC . 'inc/init.php'; include_once DOKU_INC . 'inc/plugin.php'; } global $conf; include_once dirname(__FILE__) . '/helper/jdatetime.class.php'; $pdate = new jDateTime(false, true, 'Asia/Tehran'); date_default_timezone_set('Asia/Tehran'); $query = 'INSERT INTO submissions VALUES (NULL,"' . time() . '","' . $_POST['problem_name'] . '","' . $_POST['user'] . '","' . $_POST['type'] . '",' . $_POST['status_code'] . ')'; $db = new SQLite3(DBFILE); $db->exec($query); $id = $db->lastInsertRowID(); $result_id_query = 'SELECT COUNT(*) FROM submissions WHERE problem_name = "' . $_POST['problem_name'] . '"AND username="******"'; $row_number = $db->querySingle($result_id_query); if ($conf['lang'] == "fa") { $date = $pdate->date("l j F Y H:i:s"); } else { $date = date('l j F Y H:i:s'); } if ($_POST['type'] === "output-only") { $result = array('date' => $date, 'row_number' => $row_number); } elseif ($_POST['type'] === "test-case") { $test_case_query = 'INSERT INTO submission_test_case VALUES (' . $id . ',"' . $_POST['language'] . '",' . '0,"' . $_POST['runtime'] . '")'; $db->exec($test_case_query); $result = array('date' => $date, 'row_number' => $row_number, 'id' => $id); } return $result; }
/** * Get last inserted id after insert statement */ function sql_nextid() { return $this->is_connected() ? $this->_connect_id->lastInsertRowID() : false; }
function insertID() { return $this->connection->lastInsertRowID(); }
<?php //connect to database $db = new SQLite3('../../../common/testdata.sqlite'); $operation = $_POST["webix_operation"]; // get id and data // !!! you need to escape data in real app, to prevent SQL injection !!! $id = @$_POST['id']; $rank = $_POST["rank"]; $year = $_POST["year"]; $title = $_POST["title"]; $votes = $_POST["votes"]; if ($operation == "insert") { //adding new record $db->query("INSERT INTO films(rank, title, year, votes) VALUES('{$rank}', '{$title}', '{$year}', '{$votes}')"); echo '{ id:"' . $db->lastInsertRowID() . '", mytext:"saved" }'; } else { if ($operation == "update") { //updating record $db->query("UPDATE films SET rank='{$rank}', title='{$title}', year='{$year}', votes='{$votes}' WHERE id='{$id}'"); echo '{ mytext:"saved" }'; } else { if ($operation == "delete") { //deleting record $db->query("DELETE FROM films WHERE id='{$id}'"); echo ''; } else { echo "Not supported operation"; } } }
/** * * @param string $query * @return array */ public function sendResultlessQuery($query) { $this->db->exec($query); return $this->db->lastInsertRowID(); }
/** * Tell the last inserted AUTO_INCREMENT value * * @return integer */ public function last() { //return mysql_insert_id($this->_conn); return $this->_conn->lastInsertRowID(); //return sqlite_last_insert_rowid($this->_conn); }
public function addSubscription($instagramSubscription, $type, $value, $galleryTitle, $logoFilename, $active, $printing, $displayGallery) { /* Returns subscription id */ $database = new SQLite3($this->databaseName); $command = "INSERT INTO Subscription (InstagramSubscription, Type, Value, GalleryTitle, LogoFilename, Active, Printing, DisplayGallery) VALUES('{$instagramSubscription}', '{$type}', '{$value}', '{$galleryTitle}', '{$logoFilename}', '{$active}', '{$printing}', '{$displayGallery}')"; $result = $database->query($command); $subscriptionId = $database->lastInsertRowID(); unset($database); return $subscriptionId; }
/** * {@inheritdoc} */ public function lastInsertId($name = null) { return $this->_conn->lastInsertRowID(); }
public function getGeneratedID($table) { return $this->dbConn->lastInsertRowID(); }
/** * 自增ID * @return int */ protected function lastId() { return $this->_sqlite->lastInsertRowID(); }
<?php //connect to database $db = new SQLite3('../../../common/testdata.sqlite'); $operation = $_POST["webix_operation"]; // get id and data // !!! you need to escape data in real app, to prevent SQL injection !!! $id = @$_POST['id']; $rank = $_POST["rank"]; $year = $_POST["year"]; $title = $_POST["title"]; $votes = $_POST["votes"]; if ($operation == "insert") { //adding new record $db->query("INSERT INTO films(rank, title, year, votes) VALUES('{$rank}', '{$title}', '{$year}', '{$votes}')"); echo '{ "id":"' . $db->lastInsertRowID() . '", "mytext":"saved" }'; } else { if ($operation == "update") { //updating record $db->query("UPDATE films SET rank='{$rank}', title='{$title}', year='{$year}', votes='{$votes}' WHERE id='{$id}'"); echo '{ "mytext":"saved" }'; } else { if ($operation == "delete") { //deleting record $db->query("DELETE FROM films WHERE id='{$id}'"); echo '{}'; } else { echo "Not supported operation"; } } }
<?php /* ** Скрипт возвращает последние записи в гостевой книге */ // Читаем данные, переданные в POST $rawPost = file_get_contents('php://input'); // Заголовки ответа header('Content-type: text/plain; charset=utf-8'); header('Cache-Control: no-store, no-cache'); header('Expires: ' . date('r')); // Если данные были переданы... if ($rawPost) { // Разбор пакета JSON $record = json_decode($rawPost); // Открытие БД $db = new SQLite3('gbook.db'); // Подготовка данных $author = $db->escapeString($record->author); $email = $db->escapeString($record->email); $message = $db->escapeString($record->message); $date = time(); // Запрос $sql = "INSERT INTO gbook (author, email, message, date)\n\t\tVALUES ('{$author}', '{$email}', '{$message}', {$date})"; $db->query($sql); // Возврат результата echo json_encode(array('result' => 'OK', 'lastInsertRowId' => $db->lastInsertRowID())); } else { // Данные не переданы echo json_encode(array('result' => 'No data')); }
$newUser['city'] = 'Charleston'; $newUser['state'] = 'SC'; $newUser['zip'] = '29407'; $stmt = $db->prepare('INSERT INTO users (email, pass, first, last, street, city, state, zip) VALUES (:email, :pass, :first, :last, :street, :city, :state, :zip)'); $stmt->bindValue(':email', $newUser['email'], SQLITE3_TEXT); $stmt->bindValue(':pass', $newUser['pass'], SQLITE3_TEXT); $stmt->bindValue(':first', $newUser['first'], SQLITE3_TEXT); $stmt->bindValue(':last', $newUser['last'], SQLITE3_TEXT); $stmt->bindValue(':street', $newUser['street'], SQLITE3_TEXT); $stmt->bindValue(':city', $newUser['city'], SQLITE3_TEXT); $stmt->bindValue(':state', $newUser['state'], SQLITE3_TEXT); $stmt->bindValue(':zip', $newUser['zip'], SQLITE3_TEXT); $r = $stmt->execute(); if ($r !== FALSE) { $stmt->close(); $userId = $db->lastInsertRowID(); $stmt = $db->prepare('SELECT * FROM users WHERE id=:id'); $stmt->bindValue(':id', $userId, SQLITE3_INTEGER); $rr = $stmt->execute(); $response['AddUser'] = $rr->fetchArray(SQLITE3_ASSOC); } else { $response['AddUser'] = false; } } if (isset($payloadDecoded['GetUserMovies'])) { $userId = $payloadDecoded['GetUserMovies']; $stmt = $db->prepare('SELECT * FROM movies WHERE user_id =:userId'); $stmt->bindValue(':userId', $userId['userId'], SQLITE3_INTEGER); $r = $stmt->execute(); $movies = array(); while ($row = $r->fetchArray(SQLITE3_ASSOC)) {
<?php $db = new SQLite3("database.db"); $labels = array('name' => "Name", 'address' => "Address", 'phone_num' => "Phone Number", 'email' => "Email"); if ($_GET['eid'] == "-1") { $db->exec("INSERT INTO entry (name,uid) VALUES ('New Entry'," . $_GET['uid'] . ")"); header("Location: http://aarontag.com/addressbook/edit.php?eid=" . $db->lastInsertRowID() . "&uid=" . $_GET['uid']); } if (isset($_GET['action'])) { //This is to save edits if ($_GET['action'] == "Save") { $query = "UPDATE entry SET "; foreach ($labels as $key => $val) { $query .= "{$key}='" . $_GET[$key] . "',"; } $query = trim($query, ","); $query .= " WHERE id=" . $_GET['eid']; $db->exec($query) or die("That got messed up. The query is {$query}"); header("Location: http://aarontag.com/addressbook/list.php?uid=" . $_GET['uid']); } //This is to delete an entry if ($_GET['action'] == "Delete") { $db->exec("DELETE FROM entry WHERE id=" . $_GET['eid']); header("Location: http://aarontag.com/addressbook/list.php?uid=" . $_GET['uid']); } } ?> <!DOCTYPE html> <html> <head>