PDO:sqlite doesnt INSERT data, yet no error - php

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.

Related

PHP file upload error conditions

I am trying to create a profile editing setup. It seems as though the information is edited only when an image is being uploaded. I found out that allowing the error message to be a condition allows for some more manipulation so I attempted it now my condition statement is not working as it should.
if($_FILES['files']['error']==0) {
print_r($_FILES['files']['error']);
echo "if";
foreach($_FILES['files']['name'] as $file => $name) {
$filename = $name;
try{
if(move_uploaded_file($_FILES['files']['tmp_name'][$file],'uploads/'.$filename)) {
$updateInfo = $db->prepare("UPDATE users SET image = :image, aboutme = :aboutme WHERE id = :id");
$updateInfo->bindParam(":image", $filename);
$updateInfo->bindParam(":id", $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
}
} catch(Exception $e) {
echo $e;
}
}
} elseif($_FILES['files']['error'] == 4) {
print_r($_FILES['files']['error']);
echo "Elseif";
try{
$updateInfo = $db->prepare("
UPDATE users
SET
aboutme = :aboutme
WHERE id = :id
");
$updateInfo->bindParam(':id', $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
} catch(Exception $e) {
echo $e;
}
} else{
print_r($_FILES['files']['error']);
echo "else";
}
}
When I check what array is being sent, its the correct one but the wrong condition, ie: it would run the else statement no matter the file check.
My question:
Is there something wrong with my code, with the exception of any security or efficiency flaws?
$_FILES['files']['error'] returns error code along with the file array. There are different type of error codes, all codes are mentioned in following link with details:
Please check by
print_r($_FILES['files'])
and see what are you getting in response.
As you posted your array response, you can get error code by $_FILES['files']['error'][0] or use switch case as mentioned in following link.
See here for more details:
http://php.net/manual/en/features.file-upload.errors.php
Also regarding debugging, always debug code step by step from top to bottom. Check $_POST, $_FILES, $_SERVER etc details if you get some problem particular related to data process.

PHP preg_match() steam link validation error

What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...

Get last inserted id after setting commit to false

I'm trying to insert data into two tables, if the insertion not work for one of them operation should ignored.(I think this called transaction)
try{
$dbcon=new mysqli($hn,$un,$pw,$dbn);
if($dbcon->connect_error)
throw new Exception($dbcon->connect_error);
$dbcon->autocommit(false);
$query="insert into users(id,email) values(null,'$email')";
$res_a=$dbcon->$query($query);
if($res_a){
$l_id=$res_a->insert_id;
$query="insert into profiles values($l_id,'$name','$birthday')";
$res_b=$dbcon->query($query);
}
if(!res_a || !res_b){
$dbcon->rollback();
throw new Exception("problem with database !!");
}
$dbcon->commit();
}catch(Exception $e){
echo $e->getMessage();
}finaly{
if(isset($dbcon))
$dbcon->close();
}
With this code PHP showing this Error : "Trying to get property of non-object" ...
In other words is there better way to do transaction without using autocommit methode (I'm working with mysqli)?
To answer the question and ignoring the issues with the error message this is how to run multiple updates within a transaction.
I would try retrieving the ->insert_id using the connection handle rather than the statement handle as the transaction/commit/rollback are all part of the connection handle and not the statement handle this appears to be more reliable and may be why you are not getting the error.
$dbcon=new mysqli($hn,$un,$pw,$dbn);
// if no connection can be made there is no point doing anything else
if($dbcon->connect_error) {
echo $dbcon->connect_error;
exit;
}
try{
//$dbcon->autocommit(false);
$dbcon->begin_transaction(); // this does the autocommit = false as well
$query = "insert into users(id,email) values(null,'$email')";
$res_a = $dbcon->$query($query);
if ( ! $res_a ) { // testing for FALSE is only safe way
throw new Exception($dbcon->error);
}
//$l_id = $res_a->insert_id;
$l_id = $dbcon->insert_id;
$query="insert into profiles values($l_id,'$name','$birthday')";
$res_b=$dbcon->query($query);
if( ! res_b) {
throw new Exception($dbcon->error);
}
$dbcon->commit();
}
catch(Exception $e){
echo $e->getMessage();
$dbcon->rollback();
}
finally{ // spelling correction
// not strictly necessary as PHP will close and cleanup automatically
if(isset($dbcon))
$dbcon->close();
}

is try/catch in php always working fine?

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?

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories