i made a function to delete from more tables but it does not work?
//the 'id' is came through URL so why it does not work
$id = $_GET['id'];
del($id, "DELETE FROM `companies` WHERE id=$id");
function del($id, $query){
try {
$con->query($query);
mysqli_commit($con);
echo 'Deleted';
} catch (Exception $ex) {
mysqli_rollback($con);
echo $ex->getTraceAsString();
}
}
Assuming $con is defined in the same scope as you call the function then try this.
//the 'id' is came through URL so why it does not work
$id = $_GET['id'];
del($con, "DELETE FROM `companies` WHERE id=$id");
function del($con, $query){
try {
$con->query($query);
mysqli_commit($con);
echo 'Deleted';
} catch (Exception $ex) {
mysqli_rollback($con);
echo $ex->getTraceAsString();
}
}
You should use prepared statements to prevent SQL injection attacks:
$id = $_GET['id'];
$sql = "DELETE FROM `companies` WHERE id=?";
del($id, $sql, $con);
function del($id, $sql, $con){
try {
$result = $con->prepare($sql);
$result->bind_param('i', $id);
$result->execute() === true ? 'Successfully deleted' : 'Failed: '.$con->error;
} catch (Exception $ex) {
mysqli_rollback($con);
echo $ex->getTraceAsString();
}
}
Related
This is my function.
public function getOrderValue($order_id) {
$sql = "select SUM(OD.quantity * OD.product_sell_price) from table_order_details OD where OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$user = $stmt->fetchObject();
return $user;
} catch(PDOException $e) {
return NULL;
//echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
As there is only single column in query, How to return that value? Basically i want how to fetch SUM alone instead of returning an object $stmt->fetchObject();
You can use fetchColumn, but there is nothing wrong with returning $user->total or something similar.
public function getOrderValue($order_id) {
$sql = "SELECT SUM(OD.quantity * OD.product_sell_price) AS total FROM table_order_details OD WHERE OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$total = $stmt->fetchColumn();
return $total;
} catch(PDOException $e) {
return NULL;
}
}
Assuming you're using PDO, you could use fetchColumn
http://php.net/manual/en/pdostatement.fetchcolumn.php
Code below adds data in db
$sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
$sth->execute();
$sth = null;
$sth = $this->db->prepare('
INSERT INTO
`adwords_clients_google`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`),
`client_currency` = VALUES(`client_currency`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
and I would like to add try here, something like
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (Exception $ex) {
helper::putToLog($sth->debugDumpParams(), true);
helper::putToLog("ERROR: ".$ex->getMessage(), true);
}
but i don't know should I add it for every row? How can I do that?
If you are using PDO for connecting DB then use PDOException class to handle the exception.
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (PDOException $ex) {
$Exception->getMessage(); // Error message
(int)$Exception->getCode(); // Error Code
}
I begin to despair, because I do not make a condition, if the result of the request for PDO is empty ...here is the code I use:
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
if ($res = $bdd->query($sql)){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
Ues this...
$name= $_POST['name'];
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
$res = $pdo->query($sql);
$row = $res->fetchColumn();
if ($row){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
It should $pdo instead in $bdd in query statement...basically a typo..thats all
Why would it not work to call the get_accounts() function at the end of the delete_account() function?
function get_accounts() {
require(ROOT_PATH . "inc/database.php");
try {
$results = $db->query("SELECT * FROM account");
} catch (Exception $e) {
echo ("ERROR: Data could not be retrieved from the database." . $e);
exit;
}
$accounts = $results->fetchall(PDO::FETCH_ASSOC);
return $accounts;
}
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
echo($deleteAccount);
get_accounts();
};
Basically, I want to run the delete_accounts() function and at the end I would like to run the get_accounts() function, which will refresh the list of accounts on the page after the selected account has been deleted. I can't seem to call a function from within another function, no matter what I try.
Use the finally part of the try catch & remove the 'exit();'
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
}finally{
get_accounts();
}
echo($deleteAccount);
}
Today i tired pass from the mysql connection to PDO. And i met a problem.
require('config.php');
function GetAll($query, $params) {
global $db;
try {
$sth = $db->prepare($query);
}
catch (PDOException $e) {
return null;
}
try {
$sth->execute($params);
}
catch (PDOException $e) {
return null;
}
$result = $sth->fetchAll();
return $result;
}
if ($fetch = GetAll("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`=':ipcheck'", array(":ipcheck" => $iptocheck))) {
$resultx = $db->prepare("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
$resultx->execute();
while ($rowx = $resultx->fetch()) {
;
}
$loginattempts_total = $rowx['failedattempts'];
echo "$loginattempts_total";
if ($loginattempts_total > $maxfailedattempt) {
header(sprintf("Location: %s", $forbidden_url));
exit;
}
}
this is my script. in PDO and his don't work. when my ip is banned should not see, but i see the page. PLEASE HELP ((