is try/catch in php always working fine? - php

i try to handle exception and write code as follows but i also get exception when document save sucessfully in my databse.
$table = "MyRequestTable";
$smsID = new MongoId();
$data = array("_id" => $smsID,
"requestUserid" => 2500,
"requestDate" => new MongoDate(strtotime(date('Y-m-d H:i:s'))),
"requestNosSms" => 1
);
try
{
$result = $table->insert($data, array("safe" => TRUE));
echo $smsID ;
}
catch (Exception $e)
{
echo $e->getMessage();
}
i got following exception
"Invalid modifier specified: $push"

Even if INSERT command executed correct may be situation when some other instruction throws exception. Are you sure that other parts of code are correct?

Related

Parse PHP SDK doesn't return query result

I was able to install the Parse PHP SDK (version 1.1.2) to my project and got through the quick start guide in successfully creating a TestObject. However, when I tried to query the objects, it returns nothing. I'm stuck and don't know where to go from here.
use Parse\ParseQuery;
$query = new ParseQuery('TestObject');
$results = $query->find();
foreach($results as $result){
echo $result->getObjectId() ." - " $result->get("foo") . "\n";
}
You could try it this way:
$myObj= new ParseObject("TestObject");
$myObj->set("objIdd", 1234);
$myObj->set("objName", "My Name");
try {
$myObj->save();
echo 'New object created with objectId: ' . $myObj->getObjectId();
} catch (ParseException $ex) {
// Execute any logic that should take place if the save fails.
// error is a ParseException object with an error code and message.
echo 'Failed to create new object, with error message: ' + $ex->getMessage();
}
//objectId: "XYZABC", objIdd: 1234, objName: "My Name"
$query = new ParseQuery("TestObject");
try {
$myObj = $query->get("XYZABC");
// The object was retrieved successfully.
} catch (ParseException $ex) {
// The object was not retrieved successfully.
// error is a ParseException with an error code and message.
}
Take a look at this guide.

PHP Mongo DB remove stopping proccess with no error

I'm trying to get rid of a document by _id, but the PHP process stops without error, and no error in access.log, and no output if i assign a variable to remove(). Using mongodb:
version v2.4.9
$connection = new MongoClient();
if($connection == NULL) {
return "some msg";
}
$db = $connection->main;
$collection = $db->users;
$document = $collection->findOne(array('email' => $user->email));
if($document == NULL) {
// do some stuff, works fine.
} else {
$id = $document["_id"];
echo "id=".$id // outputs: 5469a22600a8ebe8418b4567
if($document["confirm"] != "true") {
echo "confirmed not true" // outputs fine
$collection->remove(array('_id' => new MongoId($id)), true);
echo "hello!"; // never occurs
}
}
EDIT: I tried this, and no output:
try {
$collection->remove(array('_id' => new MongoId($id)), true);
} catch(Exception $e) {
echo $e->getMessage();
}
EDIT: I found an answer, but I don't understand the answer because every example I've seen includes the true argument. So I won't self answer this question and leave it up to an expert.
This doesn't work:
$collection->remove(array('_id' => new MongoId($id)), true);
This doesn't work:
$collection->remove(array('_id' => new MongoId($id)), false);
This works:
$collection->remove(array('_id' => new MongoId($id)));
I can explain your problem but I cannot explain why you are not seeing errors, there must be something odd in your PHP setup.
Anyway, as to why your boolean only value for the second parameter does not work: it is because the PHP driver expects an array: http://php.net/manual/en/mongocollection.remove.php the examples you worked from were either incredibly old (Since the change happened 1.0.5 http://php.net/manual/en/mongocollection.remove.php#refsect1-mongocollection.remove-changelog) or incorrect.

isset vs try/catch on namespaces

I'm parsing RSS feeds and have a (sub)function that looks like this:
function nSpace($nSp, $type, $i){
$namespaces = $i->getNameSpaces(true);
$exp = explode(':', $nSp);
try{
$nameSp = $i->children($namespaces[$exp[0]]);
$item[$type] = (string)$nameSp->$exp[1];
return $item[$type];
}
catch (Exception $e) { }
}
I'm trying to retrieve the namespace value, and will pass common RSS feed namespaces like "dc:date" or "content:encoded" for example as $nSp. The function works fine should the namespace exist in the XML, however the try{} is producing an 'Undefined Index' error in the first line when it doesn't.
Personally I'd rather run an isset($i->children($namespaces[$exp[0]])){} check instead of the try/catch, as I'm more familiar with that workflow, however this doesn't work (get a 'Can't use return value' error).
Few questions:
Shouldn't the try{} not produce error messages?
Is try/catch the best way?
Is there a way to do it with an if() instead?
Thanks.
Update:
Here is the (abreviated) call/usage for this function:
$rawFeed = file_get_contents($url);
try { $rss = new SimpleXMLElement($rawFeed); } catch (Exception $e) { }
foreach ($rss->channel->item as $i) {
$item['link'] = isset($i->link) ? (string)$i->link : nSpace('dc:link', 'link', $i);
$item['dateRaw'] = isset($i->pubDate) ? (string)$i->pubDate : nSpace('dc:date', 'date', $i);
// etc...
}

How to do user registration and authentication in PHP with ArangoDB?

ArangoDB is a flexible multi-model database server which has very nice features and lots of good documentation. It's a young, very promising open source project with a growing community but not many real world examples to get started.
A common real-world example, is user registration and authentication. It's needed in most applications out there.
So, how to do user registration and authentication in PHP with ArangoDB?
You can run the following example code directly and it will run through a user registration and authentication by providing some fictional user data.
It will display each step that it's doing. From collection-creation, to user-registration, authentication and finally cleaning up the collection again.
There are also lots of comments that explain what is being done, in order to make it easier to understand.
Just put this code in a file, configure the path to autoload.php according to your environment and visit its link with a browser.
This code requires ArangoDB 1.2 and up as well as the ArangoDB-PHP client version 1.2 and up.
It expects ArangoDB to be running on localhost and listening on port 8529.
Note1: The script automatically creates the 'users' collection and a unique skip-list index on 'username'. It also will drop the collection in the end.
If you want to create the collection by hand instead of automatically, you need to comment out the parts where the collection and index are created as well as the part where the collection is dropped.
After that open up a shell to ArangoDB (arangosh) and run the following commands in it:
arangosh> db._createDocumentCollection('users');
arangosh> db.users.ensureUniqueSkiplist("username");
if you want to drop the collection, type:
arangosh> db.users.drop();
Note2: I have intentionally avoided introducing more OO style, like user objects, address objects, etc.. in order to keep it simple.
So, finally here's the script.
<?php
namespace triagens\ArangoDb;
// use this and change it to the path to autoload.php of the arangodb-php client if you're using the client standalone...
// require __DIR__ . '/../vendor/triagens/ArangoDb/autoload.php';
// ...or use this and change it to the path to autoload.php in the vendor directory if you're using Composer/Packagist
require __DIR__ . '/../vendor/autoload.php';
// This function will provide us with our pre-configured connection options.
function getConnectionOptions()
{
$traceFunc = function ($type, $data) {
print "TRACE FOR " . $type . PHP_EOL;
};
return array(
ConnectionOptions::OPTION_ENDPOINT => 'tcp://localhost:8529/',
// endpoint to connect to
ConnectionOptions::OPTION_CONNECTION => 'Close',
// can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
ConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
// use basic authorization
/*
ConnectionOptions::OPTION_AUTH_USER => '', // user for basic authorization
ConnectionOptions::OPTION_AUTH_PASSWD => '', // password for basic authorization
ConnectionOptions::OPTION_PORT => 8529, // port to connect to (deprecated, should use endpoint instead)
ConnectionOptions::OPTION_HOST => "localhost", // host to connect to (deprecated, should use endpoint instead)
*/
ConnectionOptions::OPTION_TIMEOUT => 5,
// timeout in seconds
//ConnectionOptions::OPTION_TRACE => $traceFunc, // tracer function, can be used for debugging
ConnectionOptions::OPTION_CREATE => false,
// do not create unknown collections automatically
ConnectionOptions::OPTION_UPDATE_POLICY => UpdatePolicy::LAST,
// last update wins
);
}
// This function tries to persist the user data into the database upon registration
// it will fail if a user with the same username already exists.
function register($connection, $username, $password, $registrationData)
{
// This would be where you call the function that encrypts your password like you did for storage earlier
$hashedPassword = md5($password);
// assign the collection to a var (or type it directly into the methods parameters)
$collectionId = 'users';
//create an example document or an array in order to pass to the following byExample method
$document = Document::createFromArray(
array('username' => $username, 'password' => $hashedPassword, 'data' => $registrationData)
);
// Get an instance of the collection handler
$documentHandler = new DocumentHandler($connection);
try {
// query the given $collectionId by example using the previously declared $exampleDocument array
$result = $documentHandler->add($collectionId, $document);
// return the result;
return $result;
} catch (Exception $e) {
if ($e->getCode()) {
echo ('User already exists... ');
} else {
// any other error
echo ('An error occured. Exception: ' . $e);
}
}
}
// This function tries to authenticate the user and will return an array with its data
function authenticate($connection, $username, $password)
{
// This would be where you call the function that encrypts your password like you did for storage earlier
$hashedPassword = md5($password);
// assign the collection to a var (or type it directly into the methods parameters)
$collectionId = 'users';
//create an example document or an array in order to pass to the following byExample method
$exampleDocumentArray = array('username' => $username, 'password' => $hashedPassword);
// Get an instance of the collection handler
$documentHandler = new CollectionHandler($connection);
try {
// query the given $collectionId by example using the previously declared $exampleDocument array
$cursor = $documentHandler->byExample($collectionId, $exampleDocumentArray);
// check if the count of the cursor is one or not.
if ($cursor->getCount() == 1) {
// do some fancy login stuff here...
// get the current document from the cursor
$userDocument = $cursor->current();
// set session uid to the document key that was set automatically by ArangoDB,
// since we didn't provide our own on registration
$_SESSION['uid'] = $userDocument->getKey();
// extract and return the document in form of an array
return $userDocument->getAll();
} else {
return false;
}
} catch (Exception $e) {
echo ('An error occured. Exception: ' . $e . '<br>');
}
}
// register the connection to ArangoDB
$connection = new Connection(getConnectionOptions());
// register a collection handler to work with the 'users' collection
$collectionHandler = new CollectionHandler($connection);
// create the 'users' collection...
// remark those lines if you want to create the collection by hand.
echo "creating 'users' collection...";
try {
$collection = new Collection();
$collection->setName('users');
$collectionHandler->create($collection);
echo "created.<br>";
} catch (Exception $e) {
echo ('Could not create collection. Exception: ' . $e . '<br>');
}
// create unique skip list index in 'users' collection on field ''username'...
// remark those lines if you want to create the index by hand.
echo "creating unique skip list index in 'users' collection on field ''username'... ";
try {
$collection = new Collection();
$collection->setName('users');
$collectionHandler->index('users', 'skiplist', array('username'), true);
echo "created.<br>";
} catch (Exception $e) {
echo ('Could not create skip list index. Exception: ' . $e . '<br>');
}
// let's assume those variables hold your username / password
$userNameProvided = 'jane';
$passwordProvided = 'mysecretpassword';
// here we pass some structured registration data
$registrationData = array(
'name' => 'Jane',
'surname' => 'Doe',
'addresses' => array(
'email' => array('jane#doe.com', 'jane2#doe.com'),
'home' => array(
array('street' => 'Brooklyn Ave.', 'number' => 10),
array('street' => '54th Street', 'number' => 340, 'is_primary' => true)
)
)
);
// First register
echo "trying to register user for the first time... ";
$result = register($connection, $userNameProvided, $passwordProvided, $registrationData);
if ($result) {
echo " " . $userNameProvided . " registered<br>";
} else {
echo "failed<br>";
}
// Trying to register user with same username a second time
echo "trying to register user with same username a second time... ";
$result = register($connection, $userNameProvided, $passwordProvided, $registrationData);
if ($result) {
echo "registered<br>";
} else {
echo "failed<br>";
}
// now authenticate with the correct username/password combination
echo "trying to authenticate with the correct username/password combination... ";
if ($userArray = authenticate($connection, $userNameProvided, $passwordProvided)) {
echo "login successful. ";
echo '<br>';
// do some fancy after-login stuff here...
echo "<br>Welcome back " . $userArray['username'] . '!<br>';
if (count($userArray['data']['addresses']['email']) > 0) {
echo "Your primary mail address is " . $userArray['data']['addresses']['email'][0] . '<br>';
}
foreach ($userArray['data']['addresses']['home'] as $key => $value) {
if (array_key_exists('is_primary', $value)) {
$homeAddress = $userArray['data']['addresses']['home'][$key];
echo "Your primary home address is " . $homeAddress['number'] . ', ' . $homeAddress['street'] . '<br>';
// if found, break out of the loop. There can be only one... primary address!
break;
}
}
} else {
// re-display login form. +1 the wrong-login counter...
echo "wrong username or password<br>";
}
echo '<br>';
// now authenticate with the wrong username/password combination
echo "trying to authenticate with the wrong username/password combination... ";
if (authenticate($connection, $userNameProvided, 'I am a wrong password')) {
// do some fancy after-login stuff here...
echo "login successful<br>";
} else {
// re-display login form. +1 the wrong-login counter...
echo "wrong username or password<br>";
}
// truncate the collection... not needed if dropping, but only here to empty the collection of its tests
// in case you decide to not create and drop the collection through this script, but by hand.
echo "truncating collection...";
try {
$collectionHandler->truncate('users');
echo "truncated.<br>";
} catch (Exception $e) {
die ('Could not truncate collection. Exception: ' . $e . '<br>');
}
// finally drop the collection...
// remark those lines if you want to drop the collection by hand.
echo "dropping collection...";
try {
$collectionHandler->drop('users');
echo "dropped.<br>";
} catch (Exception $e) {
die ('Could not drop collection. Exception: ' . $e . '<br>');
}

PDO:sqlite doesnt INSERT data, yet no error

try
{
$res = $db->exec($sql);
if ($res === FALSE)
{
print_r($db->errorInfo());
die();
}
}
catch(PDOException $e)
{
die($e->getCode().':'.$e->getMessage());
}
catch(Exception $e)
{
die($e->getCode().':'.$e->getMessage());
}
No error info, and neither does it get caught as an exception. Yet $res is FALSE and no data gets inserted.
Array
(
[0] =>
)
But when I echo $sql and enter that query in SQLiteManager, it works inserting the data.
I used sqlite only with Python, but I had to commit insert/update statements there... Maybe that's the case here too? http://docs.php.net/manual/en/pdo.commit.php
Ensure the directory where you store file is writable.

Categories