How to Getting Error Message from SQLite Execute PHP - php

I have a simple form that inserts data into my sqlite database. It works just fine on my localhost, however, I am not getting the insert to work on my remote server. How do I get error messages if my execute() never happens or === false?
Here is my code:
if (isset($_POST["submit"])) {
$email = $_POST["Email"];
$name = $_POST["txt_Name"];
$agency = $_POST["sel_Agency"];
$subagency = $_POST["txt_SubAgency"];
$location = $_POST["txt_Location"];
$params = array(
':email' => $email,
':name' => $name,
':agency' => $agency,
':subagency' => $subagency,
':location' => $location
);
$stmt = $db->prepare($sql);
if ($stmt->execute($params) === FALSE) {
//HOW TO SHOW ERROR CODE HERE
}
}
I tried a try-catch, but didn't get anything. However, if I echo "ERROR" for example, I get the echo ERROR on screen.... I know it isn't working also, since the db has no new rows.
Any help would be appreciated. Thanks!

If you are using PDO, to get the last error use $db->errorCode() to get erro code and $db->errorInfo() get error info

Related

php header redirect before database insert

My php header("Location: example.com") seems to redirect before the database query is inserted (on one computer). Which imo is weird, because I check if the database returns true before header runs.
This works fine for me, but on my friends system it seems to redirect too early. If I remove the header() function and die(). It inserts fine.
This is coded as an Extension to mediawiki. I dont know if the problem lies here. Mediawiki has its own database query class and functions.
if ($_GET['action'] == 'postReply') {
$threadid = $_POST['t_id'];
$content = $_POST['content'];
$postReply = postThreadReply($threadid, $username, $userid,
$content);
if ($postReply == 1) {
header("Location: ?title=" . $title . "&t=" . $threadid . '#last');
die();
}
This code is adapted to be read easier.
This is the main function which the header redirects too early.
postThreadReply() do some checks and inserts into the correct tables. postThreadReply() returns 1 if each query returns true.
I don't think more code is necessary, but let me know if it is. :)
So I'm wondering if there is something wrong with my code, or within Mediawiki? Or is this a known issue with the header() function? Is there any alternative method I can try?
This is my first question here, so I'm sorry if my question is unclear or I dont provide enough code.
EDIT:
postThreadReply()
function postThreadReply($threadid, $username, $userid, $t_post) {
if (postExistDuplicate($threadid, $username, $userid, $t_post)) return 3;
if (!threadExist($threadid)) return 4;
$inpost = insertPost($threadid, $username, $userid, $t_post);
if (!$inpost) return 2;
return 1;
}
insertPost()
function insertPost($threadid, $username, $userid, $t_post) {
$datetime = date_create()->format('Y-m-d H:i:s');
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert(
'disc_posts',
array(
'id' => null,
'thread_id' => $threadid,
'author' => $username,
'author_id' => $userid,
'content' => $t_post,
'posted' => $datetime,
'deleted' => 0
)
);
return $res;
}
^ Mediawikis way of doing queries.

Recoverable fatal error: Object of class PDOStatement could not be converted to string

I am trying to send data to a database using PHP but when I execute the query using execute() I get an error that says
Recoverable fatal error: Object of class PDOStatement could not be converted to string in C:\xampp\htdocs\Code Sharing Website\submit_snippet.php on line 12
Here's my code
include 'includes/db.php';
if(isset($_POST['title']) && isset($_POST['snippet'])) {
$title = $_POST['title'];
$snippet = $_POST['snippet'];
$snippet = $db->prepare("INSERT INTO all_snippets (snippet_name, snippet_body) VALUES (:title, :snippet)");
$snippet->execute(array(
':title' => $title,
':snippet' => $snippet
));
} else {
echo "Error: Please fill out all fields";
}
You are reassigning your snippet variable to a PDO object and then try to use that in your execute. One of those variables needs to be renamed.
Changing $snippet = $_POST['snippet']; to $snippetPost = $_POST['snippet']; and your execute to this should fix it.
$snippet->execute(array(
':title' => $title,
':snippet' => $snippetPost
));

PHP MySql Picture Data

I cannot display an image from my Mysql Database.
I've kept following all the examples and other posts but can't seem to get it right...
<?php
$db = new PDO('mysql:host=localhost;dbname=MyDatabase;charset=utf8mb4', 'tester', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$request = "347";
$mytable = "u55";
$stmt = $db->prepare("SELECT * FROM ".$mytable." WHERE Id = :SearchName ");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $result[0]['TheAvatar'];
header("Content-Type: image/jpg");
echo '<img src="'.$result.'" />';
?>
My error that I have is image cannot be displayed because it contains errors.
The only difference I have from the examples is the data is stored in TEXT not BLOB/VARCHAR..
I've also tried using BinToHex() with the data to see if that made a difference.
The pictures come from a phone and are stored on a server.
The Pic data is in this link below (cant copy paste it so..)
http://spyon.agency/PicData.bmp
EDIT:
This is the code that stores the data into the DB..
It's a code snippet from the main file, the login remains the same as posted above. The Data comes from a JSON string.
$MessageDecoded = base64_decode ($request);
$input = json_decode($MessageDecoded);
Then the function that stores the data is
$mTheAvatar = $input[$i]->TheAvatar;
$mTheDirection= $input[$i]->TheDirection;
$mTheGroup = $input[$i]->TheGroup;
$mTheMedia = $input[$i]->TheMedia;
$mTheMessage = $input[$i]->TheMessage;
$mTheSenderName= $input[$i]->TheSenderName;
$mTheThumbImage = $input[$i]->TheThumbImage;
$mTheTime = $input[$i]->TheTime;
$mTheMediaExtension = $input[$i]->TheMediaExtension;
$statement = $db->prepare('INSERT INTO '.$mDevice.' '.
'(TheAvatar , TheDirection , TheGroup , TheMedia , TheMediaExtension , TheMessage , TheSenderName , TheThumbImage , TheTime) '.
'VALUES (:aTheAvatar, :aTheDirection, :aTheGroup , :aTheMedia, :aTheMediaExtension , :aTheMessage, :aTheSenderName, :aTheThumbImage, :aTheTime)');
try {
$statement->execute(array(
"aTheAvatar" => $mTheAvatar,
"aTheDirection" => $mTheDirection,
"aTheGroup" => $mTheGroup,
"aTheMedia" => $mTheMedia,
"aTheMediaExtension" => $mTheMediaExtension,
"aTheMessage" => $mTheMessage,
"aTheSenderName" => $mTheSenderName,
"aTheThumbImage" => $mTheThumbImage,
"aTheTime" => $mTheTime
));
} catch(PDOException $ex) {
echo "An Error occured!";
echo $ex->getMessage();
die;
}
you can use this code to show your image :
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result ).'"/>';

Form Post Data As Array Value

I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.
I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.
Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}

foreach Data Not Updateing in database

In my local server this script works fine. When I upload this script on live it does not work properly.
It inserts only 126 rows of data into the database, but I need to upload at least 500 rows at a time.
<?php
include 'database-config.php';
foreach($_POST['classroll'] as $row=>$classroll)
{
$sclassroll = $classroll;
$mark = $_POST['mark'][$row];
$type = $_POST['rtype'];
$session = $_POST['rsession'];
$department = $_POST['rdepartment'];
$examtype = $_POST['rextype'];
$examyear = $_POST['rexyear'];
$examsubject = $_POST['rexmarksubject'];
$stmt = $dbh->prepare("INSERT INTO exammarks(studnettype, studentsession, studentdepartment, studentclassroll, examtype, examyear, examsubjec, exammarks) VALUES (:studnettype, :studentsession, :studentdepartment, :studentclassroll, :examtype, :examyear, :examsubjec, :exammarks)");
$stmt->bindParam('studnettype', $type);
$stmt->bindParam('studentsession', $session);
$stmt->bindParam('studentdepartment', $department);
$stmt->bindParam('studentclassroll', $sclassroll);
$stmt->bindParam('examtype', $examtype);
$stmt->bindParam('examyear', $examyear);
$stmt->bindParam('examsubjec', $examsubject);
$stmt->bindParam('exammarks', $mark);
$stmt->execute();
}
header('Location: ../home.php');
?>
It is possible that your exammarks table definition on your live server contains a unique index that is not present on your local host server. If that were true some of your INSERT operations might fail.
The code you showed us doesn't check for errors. Obviously, when your program deals with high value data (such as the results of student examinations) you should check for errors.
Try this instead:
if( !$stmt->execute()) {
print_r( $arr = $stmt->errorInfo() );
}
else {
/* INSERT statement completed correctly */
}

Categories