This script is too slow, any way to improve its performance? The word is loaded by returning this function within the page, and fetching a table in the database.
The connection is via PDO and the MySQL database
function fnc_translate($texto) {
include("conn.php");
$lang['pt-br'] = 'PT_BR';
$lang['en'] = 'EN';
$lang['es'] = 'ES';
$lang['no'] = 'NO';
if(!isset($_GET['lang']) && !isset($_SESSION['lang'])){
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$_SESSION['lang'] = 'pt-br';
}elseif(!isset($_GET['lang']) && isset($_SESSION['lang'])){
$stmt = "SELECT LANG_".$lang[$_SESSION['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_SESSION['lang']];
}elseif(isset($_GET['lang'])){
$stmt = "SELECT LANG_".$lang[$_GET['lang']]." FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_".$lang[$_GET['lang']];
$_SESSION['lang'] = $_GET['lang'];
}else{
$stmt = "SELECT LANG_PT_BR FROM LANG WHERE LANG_PT_BR=:texto";
$row_name = "LANG_PT_BR";
$lang = $_SESSION['lang'] = 'pt-br';
}
try {
$sql=$conn->prepare($stmt);
$sql->bindParam(':texto',$texto,PDO::PARAM_STR);
$sql->execute();
$row=$sql->fetch();
} catch (PDOException $e) {
return $texto = $texto;
}
if(isset($row[$row_name])){
return $texto = $row[$row_name];
}else{
return $texto = null;
}
}
My problem is solved! As you already imagined, the problem was not in the code above, but in the settings in the PHP.INI of the local server. I used the Cloud settings and the speed was normalized.
Related
I run this update query from PHP code:
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
$conn is a PDO object.
The problem is that any exception is thrown by $conn, but the vehicles table in my database is not updated. So, I've tried to run this query directly through phpmyadmin, and it works correctly, so I think it's a PHP problem, but I can't figure out where the problem is.
My begin_insurance_date column is of type DATE, and $begin_insurance is a string in the correct format (YYYY-MM-DD, I've tried this code with 2017-06-10).
I'm using MySQL DBMS
This is the echo of $update_begin_insurance:
UPDATE `vehicles`
SET `begin_insurance_date` = '2017-06-10'
WHERE `plate` = 'ccccc'
UPDATE
This is the full PHP code of my page:
<?php
require_once "connect_db.php";
$plate = $_POST["plate"];
$begin_insurance = $_POST["begin_insurance"];
$end_insurance = $_POST["end_insurance"];
$fuel_economy = $_POST["fuel_economy"];
$fuel_type = $_POST["fuel_type"];
$response = array();
try
{
$conn->beginTransaction();
if ($begin_insurance != "")
{
$update_begin_insurance = "UPDATE `vehicles`
SET `begin_insurance_date` = '$begin_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_begin_insurance);
}
if ($end_insurance != "")
{
$update_end_insurance = "UPDATE `vehicles`
SET `end_insurance_date` = '$end_insurance'
WHERE `plate` = '$plate'";
$conn->query($update_end_insurance);
}
if ($fuel_economy != "")
{
$update_fuel_economy = "UPDATE `vehicles`
SET `fuel_economy` = $fuel_economy
WHERE `plate` = '$plate'";
$conn->query($update_fuel_economy);
}
if ($fuel_type != "")
{
$update_fuel_type = "UPDATE `vehicles`
SET `id_fuel` = $fuel_type
WHERE `plate` = '$plate'";
$conn->query($update_fuel_type);
}
$response["post"] = $_POST;
$response["error_code"] = "0";
$response["error_message"] = "none";
$response["driver_error_code"] = "0";
}
catch (PDOException $e)
{
if ($conn->inTransaction())
{
$conn->rollBack();
}
$response["post"] = $_POST;
$response["error_code"] = $e->getCode();
$response["error_message"] = $e->getMessage();
$response["driver_error_code"] = $e->errorInfo[1];
}
echo json_encode($response);
?>
As I said before, I don't get any exception (as you can see, I also print the $_POST array to check if the params are received correctly, and yes, they are).
This is what echo json_encode($response) prints:
{
"post":
{
"plate":"ccccc",
"begin_insurance":"2017-06-10"
},
"error_code":"0",
"error_message":"none",
"driver_error_code":"0"
}
I'm sure the connection works correctly because I've got others PHP files which execute some INSERT queries, and they works correctly.
I've solved the problem, I was missing the $conn->commit().
I'm building a custom CMS and I'm trying to create multilingual content by using MySQL with column approach. I'm not using any framework, it's pure PHP.
Here's my code:
<?php
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$title = $row['title'];
}
echo $title;
?>
I'm successfully printing the title from the database.
Now if I change the table posts by adding a new fields "title_en" and "title_de" and add a session
$_SESSION['current_language'] = 'en';
$_SESSION['current_language'] = 'de';
How can I create a language switcher and print the title depends what language is activated?
EDIT:
Here's the code that I'm trying
<?php
session_start();
if(isset($_GET['lang']) && in_array($_GET['lang'],['en','de'])) {
$lang = $_GET['lang'];
$_SESSION['current_language'] = $lang;
print_r($_SESSION['current_language']);
} else {
$lang = isset($_SESSION['current_language']) ? $_SESSION['current_language'] : 'en';
}
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$title = $row['title_'.$lang];
echo $title;
}
?>
but on www.mywebsite.com/lang=de it still shows the English title.
EDIT2
I've just tried www.mywebsite.com/?lang=de and it's displaying properly. Big thanks to Павел Иванов!
Just use saved language as key. get attribute should have more priority than session saved ( for example when user want to switch language ).
if(isset($_GET['lang']) && in_array($_GET['lang'],['en','de'])) {
$lang = $_GET['lang'];
$_SESSION['current_language'] = $lang;
} else {
$lang = isset($_SESSION['current_language']) ? $_SESSION['current_language'] : 'en';
}
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$title = $row['title_'.$lang];
echo $title;
}
Edit:
language switcher is simple ul>li list in url with lang="Your lang"
At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?
I need your help figuring this out. I am trying to have a reserve a book functionality in my project. I don't have any error with this one but my oop functions that contains the pdo statements won't work. Particulary with the insert (values can't be inserted into the database) and update(can't update existing info from the database) part. I don't know why this happens.
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve($id,"book_info");
if(isset($_POST['reserve']))
{
foreach($result as $row)
{
echo $oldstock=$row['quantity'];
}
echo $newstock = $oldstock-1;
$code->minusbookreserve($quantity, $newstock,"book_info");
$code->insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,"reserve_list");
// echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
else {
echo "<script type='text/javascript'>alert('Something went wrong.');window.location='bookReservelist.php';</script>";
}
?>
codex_books.php
public function minusbookreserve($quantity, $newstock, $table)
{
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
if($stmt){
return true;
}
else {
return false;
}
}
public function insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,$table)
{
$q = "INSERT INTO $table SET sid= :sid ,sname=:sname,title=:title,author=:author,isbn=:isbn,publisher=:publisher,language=:language, genre=:genre, quantity=:quantity, date_to_be_borrow=:date_to_be_borrow";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':sid'=>$sid,':sname'=>$sname,':title'=>$title,':author'=>$author,':isbn'=>$isbn,':publisher'=>$publisher,':language'=>$language, ':genre'=>$genre,':quantity'=>$quantity,':date_to_be_borrow'=>$date_to_be_borrow));
return true;
}
Given:
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
^^^^^^^^^^^
Where's book_title here?
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
You really MUST check return values from your DB calls for boolean FALSE, indicating failure. You're simply assuming everything will always succeed, which is a very BAD way of writing code.
Below is the function I am using. It is strange because when I test the name "admin" it returns an associative array with all the correct columns and values, however every other name tests returns 0 as far as I can tell, meaning nothing is found from the query (I am entering the names perfectly as they are in the database).
I have a feeling this could be some sort of security feature of pdo or something but I don't understand why it is acting up this way.
I am using mysql.
Does anyone know the problem and how to resolve it? Thank you!
function getUserDetailsByName($name, $fields = "*")
{
$db = connect_db();
$query = "SELECT $fields FROM UserDetails WHERE userName=:username";
$result = $db->prepare($query);
$result->bindParam(":username", $name);
if (!($result->execute())) {
sendMessage (1,1,'Query failed',$query);
$db = null;
return;
}
if (!($result->fetch(PDO::FETCH_NUM) > 0)) {
$db = null;
return 0;
}else{
$result = $result->fetch();
$db = null;
return $result;
}
}
EDIT: Someone asked to post how I call the function.
$user = getUserDetailsByName($_POST['value']);
if($user == 0)
{
print "user = 0";
}
print_r($user);
function getUserDetailsByName($name, $fields = "*"){
$db = connect_db();
$query = "SELECT {$fields} FROM UserDetails WHERE userName = :username LIMIT 1;";
if(!$result = $db->prepare($query)){
return null;
}
$result->bindParam(":username", $name);
if(!$result->execute()) {
sendMessage (1,1,'Query failed',$query);
return null;
}
if(!$user = $result->fetch(PDO::FETCH_NUM)) {
return false;
}
return $user;
}
Why 2 fetches? Checkout and compare this to your code.
Use like this:
if($user = getUserDetailsByName($_POST['value'])){
// we have a user!
}else{
// we don't have a user!
}