After executing the SQL file below to create the appropriate tables(which gets executed correctly without errors),
<?php
try {
require_once 'dbcon.php';
$sql_file = 'mysql.sql';
$contents = file_get_contents($sql_file);
$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/',
'/\s*--.*\n/',
'/\s*#.*\n/',
);
$contents = preg_replace($comment_patterns, "\n", $contents);
$statements = explode(";\n", $contents);
$statements = preg_replace("/\s/", ' ', $statements);
foreach ($statements as $query) {
if(trim($query) != '') {
$db->query($query);
if ($db->errno) {
throw new Exception("Fail to load data in database (".$db->errno.")");
}
}
}
Running the following query right after the foreach gets executed successfully without errors and success message gets printed. However , no data gets inserted into the database.
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
$cstmt->execute();
if($cstmt->affected_rows === 1){
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}
?>
I have printed out $cstmt->error and $cstmt->errno and they all return 0 . which seems fine but don't why the data doesn't get inserted into the fields. Anything am missing or doing wrong?
Try this:
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
**if($cstmt->execute()){**
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}
Related
when executing the form, the data is not inserting. I have activated SQLITE3 and I am not skipping any type of error.
The echo of the try is to see what was wrong but nothing. I see everything right.
Does anyone help me?
$username = $_POST['nombre'];
$clave = $_POST['clave'];
$apenom = $_POST['apenom'];
try {
$bd = new SQLite3("test");
//preparamos la sentencia
echo "INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')";
$bd->exec("INSERT INTO usuarios (username,clave,apenom) VALUES ('$username','$clave','$apenom')");
/* while ($row = $resultado->fetchArray()) {
echo "{$row['username']} {$row['clave']} {$row['apenom']} \n";
} */
} catch (\Throwable $th) {
echo $th;
}
Do take the advice from the comments into account, database security is not something you should 'wing'...
As for a little help on setting up a connection and importantly debugging if anything goes wrong so you know what to fix, the following 'skeleton' might help:
<?php
try {
// connect to your database
$sqlite = new SQLite3('test.db');
}
catch (Exception $e) {
// if no connection could be established a exception is thrown
echo $e->getMessage();
}
// your query
$query = '...';
$result = $sqlite->query($query); // result object (FALSE on error)
if (!$result) {
// query failed for some reason...
echo $sqlite->lastErrorMsg();
} else {
// do something with result
}
I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}
Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
the try/catch method is not working compared to my previous store function that is working
Read up further on findOrFail. You can catch the exception it throws when it fails to find.
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
I have a problem. I have set up the Twilio helper library in PHP to send SMS and everything works fine. But I need to do something and I cant figure out how to do it.
Here is the working code:
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
if(!$sms){ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
} else {
$count=0;
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
Everything works fine. The problem is when an error happens because of a broken phone, the loop which goes through the array breaks and sending stops. I need to keep sending, how could I do this? This is controller and requests is sent from ajax call, thats why there are echo statements!
When exception throws, the foreach loop breaks and execution comes to catch
So make your code as
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
try
{
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
An additional try catch block within foreach loop
Here's the same code but a bit trimmed... This worked for me!
<?PHP
require "Services/Twilio.php";
// Set our AccountSid and AuthToken from twilio.com/user/account
$AccountSid = "{ACCOUNTSID}";
$AuthToken = "{AUTHTOKEN}";
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);
/* Your Twilio Number or Outgoing Caller ID */
$from = '2126404004';
$people = array("212-716-1130");
$body = "Enter your text message here";
$errorIds = array(); //user ids array which had broken phones
foreach ($people as $to) {
try
{
$client->account->sms_messages->create($from, $to, $body);
echo "Sent message to: $to \n <br>";
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $to);
}
}
print_r($errorIds);
?>
Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'