$prepStatement->execute(array_values($inv)); does not work - php

i can't find the solution.
$prepStatement->execute(array_values($inv)); does not work
I got an error at this line.
my php script:
<?php
$response=array();
$json = $_REQUEST['json'];
$data = json_decode($json);
var_dump(json_decode($json, true));
print "Starting request". "<br/>";
if($_SERVER['REQUEST_METHOD'] == "POST" && (json_last_error() === JSON_ERROR_NONE))
{
if($data->connection && $data->wykazy)
{
print "connection and wykazy exist". "<br/>";
if ($data->connection->Host && $data->connection->db && $data->connection->User && $data->connection->password) {
print "connection Host, db, User, password are OK". "<br/>";
try
{
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbObj = new PDO('mysql:host='.$data->connection->Host.';dbname='.$data->connection->db, $data->connection->User, $data->connection->password, $opt);
print "Proba ustanowienia polaczenia! Bledy: " . $dbObj->errorCode() . "<br/>";
createWykaz($dbObj, $data);
}
catch (PDOException $e)
{
print "Blad podczas tworzeniu obiektu dbObj!: " . $e->getMessage() . "<br/>";
$response["success"]=0;
$response["message"]="Can not connect to database!: " . $e->getMessage();
echo json_encode($response);
die();
}
//$mysqli = new mysqli($data->connection->Host, $data->connection->User, $data->connection->password, $data->connection->db);
}
}
else
{
print "connection i wykazy nie istnieją! " . "<br/>";
$response["success"]=0;
$response["message"]="Error: Required fields are missing!";
echo json_encode($response);
}
}
function createWykaz($dbObj, $data)
{
try{
$allowedVariables = array(
'wyk_ilosc',
'wyk_czasod',
'wyk_czasdo',
'wyk_id_czynnosc',
'wyk_id_pracownik',
'wyk_id_partia',
'wyk_status',
);
$sql = "insert into wykaz (". implode(',', $allowedVariables) .")";
$sql.= " VALUES (". substr(str_repeat('?,', sizeof($allowedVariables)), 0, -1) .");";
print "sql: ". $sql . "<br/>";
if($prepStatement = $dbObj->prepare($sql)){
//edit
$dbObj->beginTransaction();
foreach ( $data->wykazy as $inv ) {
$res = $prepStatement->execute(array_values($inv));
}
/*
$prepStatement = $dbObj->prepare($sql)
foreach ($data->wykazy as $row) {
$dbObj->executeMultiple($prepStatement, $row);//return DB_OK
}
*/
$response["success"]=1;
$response["message"]="Wszystkie wykazy successfully added to Database!";
echo json_encode($response);
$dbObj->commit();
}
else {
$response["success"]=0;
$response["message"]="Błąd podczas przygotowania zapytania!"+ $prepStatement;
echo json_encode($response);
}
$dbObj=null;
$prepStatement=null;
}catch(PDOException $e){
//Error handling goes here
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $e->getMessage() . "\n";
$response["success"]=0;
$response["message"]="Our query failed to execute!". $e->getMessage();
echo json_encode($response);
$dbObj=null;
$prepStatement=null;
}
}
?>
it works till:
$prepStatement->execute(array_values($inv));
I am getting an error at this position, but $data->wykazy is an array.
I can change my code to:
$sth = $db->prepare('INSERT INTO numbers VALUES (?, ?, ?)');
foreach ($alldata as $row) {
$db->execute($sth, $row);
}
but I will try the other way.
Thanks for help
Sebastian
The output from Postman:
Postman part1
Postman part2

Related

Updating price and stock of thousands of entries in DB

I'm working on a project to update a daatabase of products (price and stock) in prestashop based on data from a vending program. I'm doing this using PHP code and a MySQL conneectio to the DB.
The problem is that there is about 58.000 products and it seems to take very long to update all products.
Here is my code:
<?php
$host = '127.0.0.1';
$uname = '*******';
$pwd = '*******';
$db = "*******";
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
echo 'Updating init...' . "<br>";
//Create an instance of the class Update to get and update the data
$update = new Update();
try
{
// Get the product list from prestashop's DB
$productsFromPS = $update->getProductListFromPS($con);
// Cycle through all the product IDs
foreach ($productsFromPS as $product)
{
// Id of the product
$id = (int) $product['id_product'];
// Price from PS
$pricePS = (float) $product['price'];
// Get the product's stock from PS
$stockPS = $update->getProductStockFromPS($con, $id);
// Physical and reserved quantities in PS
$physQty = $stockPS['physical_quantity'];
$resQty = $stockPS['reserved_quantity'];
// Get product's price and stock from Vendus
$priceAndStockVendus = $update->getPriceAndStockFromVendus($id);
// Price from Vendus
$priceVendus = (float) $priceAndStockVendus[0];
// Tools for float compardsion
$zero = (float) 0.00;
$epsilon = (float) 0.00001;
// If the price in Vendus is 0, put 0 to stock in PS
if(!(abs($priceVendus-$zero) < $epsilon))
$stockVendus = (int) $priceAndStockVendus[1];
else
$stockVendus = 0;~
// If the prices do not match, update price
if(!(abs($pricePS-$priceVendus) < $epsilon))
$update->updatePrice($con, $id, $priceVendus);
// If the stocks do not matcth, update stock
if ($stockVendus!=$physQty)
$update->updateStock($con, $id, $stockVendus, $resQty);
}
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
/*
Class which method to get and update data
*/
class Update
{
public function getProductListFromPS ($con)
{
try
{
$sql_q = mysqli_query($con,"SELECT `id_product`, `price` FROM `ps_product` ORDER BY `id_product` ASC");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo '4: ' . $output[4]['id_product'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output;
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage() . '<br>';
}
}
public function getProductStockFromPS ($con, $id)
{
try
{
$sql_q = mysqli_query($con,"SELECT `quantity`, `physical_quantity`, `reserved_quantity` FROM `ps_stock_available` WHERE `id_product` = $id");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo 'qty: ' . $output[0]['quantity'] . "<br>";
//echo 'phys qty: ' . $output[0]['physical_quantity'] . "<br>";
//echo 'res qty: ' . $output[0]['reserved_quantity'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output[0];
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function getPriceAndStockFromVendus ($id)
{
try
{
$url = 'https://www.vendus.pt/ws/v1.1/products/';
$apiKey = '***********';
$method = 'GET';
$params = array(
'reference' => $id,
);
$url .= '?' . http_build_query($params);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $apiKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
//echo 'URL to Vendus - ' . $url . '<br />';
$result = curl_exec($curl);
$resultArray = json_decode($result, true);
curl_close($curl);
return array($resultArray[0]['gross_price'], $resultArray[0]['stock']);
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updatePrice ($con, $id, $price)
{
try
{
$sql_q = mysqli_query($con,"UPDATE `ps_product` SET `price` = '$price' WHERE `id_product` = '$id'");
$sql_q = mysqli_query($con,"UPDATE `ps_product_shop` SET `price` = '$price' WHERE `id_product` = '$id' AND `id_shop` = '1'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Price updated (' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updateStock ($con, $id, $stock, $resQty)
{
try
{
$newPhysQty = $stock;
if ($newPhysQty!=0)
$newQty = $newPhysQty - $resQty;
else
$newQty = 0;
$sql_q = mysqli_query($con,"UPDATE `ps_stock_available` SET `physical_quantity` = '$newPhysQty', `quantity` = '$newQty' WHERE `id_product` = '$id'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Stock updated(' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
}
}
?>
The plan is to have this code run at certain intervals to keep the DB updated.
Am I doing something wrong? Is there a faster way to do this?
This code is running on a server with 2GB of RAM and not a very fast processor. Should it be ruinning on a computer with higher specs?
I will appreciate any remarks/critcs about the code and tips on how to improve it.
Thanks in advance! ;)
EDIT: It appears running the code produces a 500 Internal Server Error, any idea what could be causing this? If I run the foreach only once it doesn't occur. How can i check the error in detail? I have CPannel as the control panel for the server.

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

printing out a json array

I am trying to figure out how to print a json array. I am trying to handle this from Android code but it is not working. I believe the problem lies in how I am outputting json. the below doesn't show anything. The script is below:
<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
}
$sql='SELECT title, description, country, city, rate FROM discounts';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>
thanks in advance
You can only call json_encode once. You're double-encoding everything.
The line where you're adding data to the array needs to be
$json[] = $row;
Then, when the array is built up, you encode the entire thing in one single call:
echo json_encode($json);
You call json_encode twice. To fix it, change your code to:
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = $row;
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>

data added with a prepared statement can't be searched with WHERE

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;
?>

Categories