Iam trying to create a JSON object out of my SQL data in PHP. How to do that?
This is my approach, which does not work so far.
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros = "[";
while ($result = $query->fetch()) {
if ($registros != "[") {
$registros .= ",";
}
$registros .= '{"id": "' . $result["id"] . '",';
$registros .= '"name": "' . $result["name"] . '"}';
$registros .= '"salary": "' . $result["salary"] . '"}';
$registros .= "]";
echo $registros;
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>`
Why dont you try the json_encode() for this ? Why you try for unnecessary while loop.
$query = $conn->prepare('SELECT id, name, salary from afreen');
Then try the json_encode() to get the Data in Json format.
Sources - http://php.net/json_encode
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros= [];
while ($result = $query->fetch()) {
array_push($registros,array(
'id' =>$result["id"],
'title' =>$result["name"],
'salary' =>$result["salary"]
));
$output = json_encode(array("product"=>$registros));
print_r($output);
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
Related
So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.
From the code below, i need help on how I can print something like this:
echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
This is the code I need to be modified :
<?php
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
}
echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Just like you normally would print results of SELECT query. Although here it seems there's an ajax call invovled.
header("Content-Type:application/json");
try {
$db_name = 'test_db';
$db_user = 'test_db_user';
$db_password = 'EXAMPLE_PASSWORD';
$db_host = 'localhost';
$memcache = new Memcache();
$memcache->addServer("127.0.0.1", 11211);
$sql = 'SELECT
product_id,
product_name,
retail_price
FROM products
';
$key = md5($sql);
$cached_data = $memcache->get($key);
$response = [];
$result = null;
if ($cached_data != null) {
$response['Memcache Data'] = $cached_data;
$result = $cached_data;
} else {
$pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute();
$products = [];
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
$products[] = $row;
}
$memcache->set($key, $products, false, 5);
$response['MySQL Data'] = $products;
$result = $products;
}
// echo json_encode($response, JSON_PRETTY_PRINT) . "\n";
$html = "";
foreach ($result as $row) {
$html .= "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "
. " - Price: ". $row["retail_price"] . "<br>";
}
// return as HTML (won't work in ajax)
echo $html;
// or for ajax:
echo json_encode($html, JSON_PRETTY_PRINT) . "\n";
// or
echo json_encode(["html" => $html], JSON_PRETTY_PRINT) . "\n";
} catch(PDOException $e) {
$error = [];
$error['message'] = $e->getMessage();
echo json_encode($error, JSON_PRETTY_PRINT) . "\n";
}
Objective: Take a data entry that contains multiple dates in "$column4" and for each date, create a new entry with $column2, $column3, $column4 and a date followed by one comment.
For this example let's say that:
$column1 is an auto-incrementing primary ID
$column2 = '20141122001';
$column3 = 'something';
$column4 = 'else';
$string = '12/29/2014 2:44PM - working with the lender to remove the mortgage late so we are able to refinance the client. - Person 1 12/04/2014 2:27PM - file suspended until rapid rescore comes back removing late payment from credit. - Person 2';
The example below works for two dates, but how about 1-20 dates? Thanks in advance.
<?php
$host = 'localhost';
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
$db_name = 'intergl8_test';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
echo $string . "<br>";
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches))
{
$date = $matches[2];
}
echo $date;
//////////////////////
if (isset($date)) {
$newstring = str_replace($date,"",$string);
if(preg_match('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $newstring, $matches))
{
$date2 = $matches[2];
}
}
echo "<br>";
echo $date2;
////////////////
echo "<br>";
$parts = parse_url($string);
$path_parts= explode($date2, $parts[path]);
$user = $path_parts[1];
$user2 = $path_parts[0];
//$user3 = $path_part[2];
echo $date2 . " " . $user . "<br>";
echo $user2 . "<br>";
$newdate = $date2 . " " . $user;
//echo $user3;
?>
<?php
$db_user = 'intergl8_james';
$db_pass = 'Interglobalsecure2014';
try {
$pdo = new PDO('mysql:host=localhost;dbname=intergl8_test', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $newdate
));
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $user2
));
# Affected Rows?
echo $stmt->rowCount() ." row(s) inserted."; // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
UPDATE:
<?php
$host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name.'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM test');
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
$string = $row[4];
// $column1 = $row[0]; just the ID, don't need to copy
$column2 = $row[1];
$column3 = $row[2];
$column4 = $row[3];
?>
<?php
preg_match_all('/(.*)([0-9]{2}\/[0-9]{2}\/[0-9]{2,4})(.*)/', $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "<br>";
/* echo "part 1: " . $val[1] . "<br>";
echo "part 2: " . $val[2] . "<br>";
echo "part 3: " . $val[3] . "<br>";
echo "part 4: " . $val[4] . "<br><br>"; */
// start crazy shit
$db_user = '';
$db_pass = '';
$db_name = '';
try {
$pdo = new PDO('mysql:host=localhost;dbname='..'', $db_user, $db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO test2 VALUES(:id,:number,:blah,:cool,:notes)');
$stmt->execute(array(
':id' => '', ':number' => $column2, ':blah' => $column3, ':cool' => $column4, 'notes' => $val[0]
));
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
// end crazy shit
}
?>
<?php
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
I wonder if someone could advise me here. I have a page where I am updating information in a database, from the previous page I post any new images (with a caption too) and I have a checkbox for deleting images. On the processing page I have the following code:
<?php
session_start();
$dbhost = 'removed';
$dbuser = 'removed';
$dbpass = 'removed';
$dbname = 'removed';
function reArrayFiles($file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$soldier_pre_images = explode(",", $row['soldier_images']);
}
if($_POST['deletephoto']){
$imagestodelete=$row['soldier_images'];
$captionstodelete=$row['soldier_images_captions'];
foreach($_POST['deletephoto'] as $todelete){
$deleteexplode = explode("--",$todelete);
echo $deleteexplode;
$deleteexplodepath = $deleteexplode[0];
$deletecaption=$deleteexplode[1];
$imagesafterdelete= str_replace($deleteexplodepath.",","",$imagestodelete);
echo $imagesafterdelete;
$captionsafterdelete = str_replace($deletecaption."--","",$captionstodelete);
echo $captionsafterdelete;
$unlinkpath = str_replace('site url','..',$deleteexplodepath);
unlink($unlinkpath);
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $imagesafterdelete, ":captions" => $captionsafterdelete, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
if ($_FILES['photo']) {
$file_ary = reArrayFiles($_FILES['photo']);
$capcount = 0;
foreach ($file_ary as $file) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $file["name"]);
$extension = end($temp);
if ((($file["type"] == "image/gif")||($file["type"] == "image/jpeg")||($file["type"] == "image/jpg")||($file["type"] == "image/pjpeg")||($file["type"] == "image/x-png")||($file["type"] == "image/png"))&&($file["size"] < 9000000) && in_array(strtolower($extension), $allowedExts)) {
if ($file["error"] > 0) {
$file_error = "Return Code: " . $file["error"] . "<br>";
} else {
$newfilename = "../assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$file_fullname = "site urlv/assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$new_caption = $_POST['image_captions'][$capcount];
if (file_exists($newfilename)) {
$file_exists = $file["name"] . " already exists. ";
} else {
if(is_dir("../assets/uploads/images/" . $_POST['soldier_id'])){
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}else{
mkdir("../assets/uploads/images/" . $_POST['soldier_id'], 0777, true);
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}
}
if (strlen($row['soldier_images'])>1){
$uploaded_images = $row['soldier_images'] . ",". $uploaded_images;
}else{
$uploaded_images = $uploaded_images;
}
}
} else {
$file_invalid = "The file is not a jpg/gif/png file, or is larger than 20mb. Please try again.";
}
$capcount = $capcount+1;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $uploaded_images, ":captions" => $uploaded_captions, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$firstname = $row['firstname'];
$surname = $row['surname'];
$yearofbirth = $row['yearofbirth'];
$dateofdeath = date("d/m/Y", strtotime($row['dateofdeath']));
$ageatdeath = $row['ageatdeath'];
$regiment = $row['regiment'];
$battallion_brigade = $row['battallion_brigade'];
$Coybty = $row['Coy/bty'];
$rank = $row['rank'];
$solider_number = $row['soldier_number'];
$Next_of_Kin = $row['Next_of_Kin'];
$CWGC = $row['CWGC'];
$Place_Died = $row['Place_Died'];
$Connection_to_Wymeswold = $row['Connection_to_Wymeswold'];
$Cemetery = $row['Cemetery'];
$LRoH = $row['LRoH'];
$Grave = $row['Grave'];
$Memorial = $row['Memorial'];
$Pier_Face = $row['Pier_Face'];
$Other_Mem = $row['Other_Mem'];
$Other_Details = $row['Other_Details'];
$soldier_images = explode(",", $row['soldier_images']);
$soldier_images_captions = explode("--", $row['soldier_images_captions']);
}
$dbo = null;
?>
This isn't a live site right now and is in testing/dev. However the issue I am seeing is that, all the queries are running, but the page loads up as though the select has run first (by this I mean that the records returned are those from before the updates as processed. Can I force this select to run last so that it gets the latest records?
I think you get the 'original' data on the last select because you are running the queries on different connections. Hence they will live in isolated transactions, that might not be properly committed when the last select runs.
If you run them all in the same PDO object I think it will work.
(If you take POST parameters and concatenate them into SQL your server will be hacked. It's just a matter of time and you have the URL here for everyone to see.)
The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}
Data that I add inside an SQLite3 db using prapared statements are not searchable with WHERE:
SELECT Active FROM Users WHERE Username="john"
I have a demonstration in PHP that adds data with a prepared and a direct statement and then tries to search for them.
My questions are two:
Why is this happening?
How can I search data that I add through prepared statements?
Here is the PHP script.
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Helsinki');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding("UTF-8");
header('Content-Type: text/html; charset=UTF-8');
$timezone = date('Z');
$db = '';
// ---
//
// adds a user in the db with a prepared statement
//
function add_user1($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$statement = "INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES (:Username,:Password,:Time,:Timezone,:Active);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $name, SQLITE3_TEXT);
$query->bindValue(':Password', $pass, SQLITE3_TEXT);
$query->bindValue(':Time', $time, SQLITE3_INTEGER);
$query->bindValue(':Timezone', $timezone, SQLITE3_INTEGER);
$query->bindValue(':Active', '1', SQLITE3_INTEGER);
$ok = $query->execute();
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// adds a user in the db with a direct execution
//
function add_user2($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$db->exec('INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES ("' . $name . '", "' . $pass . '", ' . $time . ', ' . $timezone . ', 1);');
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// seeks a password for a given username
//
function seek($user)
{
global $timezone;
global $db;
try
{
// previous tests showed that this doesn't work on all cases
$result = $db->query('SELECT Password FROM Users WHERE Username="'. $user . '"');
foreach ($result as $row)
{
$password = $row['Password'];
echo "search through SQLite: password for $user is $password\n";
}
$result = $db->query("SELECT * FROM Users");
foreach($result as $row)
{
$username = $row['Username'];
$password = $row['Password'];
if ($username == $user)
{
echo " search through array: password for $username is $password";
break;
}
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
// ---
echo "<pre>\n";
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL, Time INTEGER UNIQUE NOT NULL, Timezone INTEGER NOT NULL, Active BOOLEAN NOT NULL);");
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
add_user1("Bob", "cat");
sleep(1);
add_user1("Mark", "dog");
sleep(1);
add_user2("John", "mouse");
sleep(1);
add_user2("Alice", "rodent");
try
{
$result = $db->query('SELECT * FROM Users');
foreach ($result as $row)
{
echo " Id: " . $row['Id'] . "\n";
echo "Username: " . $row['Username'] . "\n";
echo "Password: " . $row['Password'] . "\n";
echo " Time: " . $row['Time'] . "\n";
echo "Timezone: " . $row['Timezone'] . "\n";
echo " Active: " . $row['Active'] . "\n";
echo "\n";
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
seek("Alice");
echo "\n\n";
seek("Mark");
$db = NULL;
?>
Someone told me I should remove the types on the binding. I did and it works :)
Thanks anyone who read it.
Here is the full working example.
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Helsinki');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding("UTF-8");
header('Content-Type: text/html; charset=UTF-8');
$timezone = date('Z');
$db = '';
// ---
//
// adds a user in the db with a prepared statement
//
function add_user1($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$statement = "INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES (:Username,:Password,:Time,:Timezone,:Active);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $name);
$query->bindValue(':Password', $pass);
$query->bindValue(':Time', $time);
$query->bindValue(':Timezone', $timezone);
$query->bindValue(':Active', '1');
$ok = $query->execute();
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// adds a user in the db with a direct execution
//
function add_user2($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$db->exec('INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES ("' . $name . '", "' . $pass . '", ' . $time . ', ' . $timezone . ', 1);');
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// seeks a password for a given username
//
function seek($user)
{
global $timezone;
global $db;
try
{
// previous tests showed that this doesn't work on all cases
$result = $db->query('SELECT Password FROM Users WHERE Username="'. $user . '"');
foreach ($result as $row)
{
$password = $row['Password'];
echo "search through SQLite: password for $user is $password\n";
}
$result = $db->query("SELECT * FROM Users");
foreach($result as $row)
{
$username = $row['Username'];
$password = $row['Password'];
if ($username == $user)
{
echo " search through array: password for $username is $password";
break;
}
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
// ---
echo "<pre>\n";
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL, Time INTEGER UNIQUE NOT NULL, Timezone INTEGER NOT NULL, Active BOOLEAN NOT NULL);");
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
add_user1("Bob", "cat");
sleep(1);
add_user1("Mark", "dog");
sleep(1);
add_user2("John", "mouse");
sleep(1);
add_user2("Alice", "rodent");
try
{
$result = $db->query('SELECT * FROM Users');
foreach ($result as $row)
{
echo " Id: " . $row['Id'] . "\n";
echo "Username: " . $row['Username'] . "\n";
echo "Password: " . $row['Password'] . "\n";
echo " Time: " . $row['Time'] . "\n";
echo "Timezone: " . $row['Timezone'] . "\n";
echo " Active: " . $row['Active'] . "\n";
echo "\n";
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
seek("Alice");
echo "\n\n";
seek("Mark");
$db = NULL;
?>