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
Related
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();
}
}
I have the following statement which SELECTs ProductName and Quantity from the orderDetails table. See below:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
$_POST['ProductName'] = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
If $_POST['ProductName']['ProductName'] exists more than once how can I create a foreach loop based on that?
What I have tried so far...
foreach($_POST['ProductName']['ProductName']) {
}
This did not work...
What have I done wrong?
Complete Code:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
array_push($_POST["ProductName"], $stmt->fetch(PDO::FETCH_ASSOC));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['ProductName']['ProductName'];
// echo $_POST['ProductName']['Quantity'];
try {
$stmt1 = $conn->prepare("SELECT Stock FROM products WHERE ProductName = :ProductName");
$stmt1->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt1->execute();
$_POST['Stock'] = $stmt1->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['Stock']['Stock'];
$_POST['DEDUCT'] = $_POST['Stock']['Stock'] - $_POST['ProductName']['Quantity'];
try {
$stmt2 = $conn->prepare("UPDATE products SET Stock = :Stock WHERE ProductName = :ProductName");
$stmt2->bindParam(':Stock', $_POST['DEDUCT']);
$stmt2->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt2->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You can make a new array called (for example, $rows) which contains all of the fetched data using the function fetchAll() (fetch() only retrieves the next one row).
The most straightforward way to do this is as follows:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
//Add all returned values to an array called "$rows"
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then if you want to access that data later you can do:
foreach($rows as $row){
var_dump($row); //Show the data in the row to double-check
}
You can create array using foreach like this :
$newval_arr = array();
foreach($_POST['ProductName']['ProductName'] as $key=>$value) {
if(!in_array($value,$newval_arr) || empty($newval_arr))
{
$newval_arr[] = $value;
}
}
Then after you can use $newval_arr in foreach
foreach($newval_arr as $key=>$value)
{
//Your code herer
}
I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
I have two connection string user DBO:
string1:
try {
$conn1 = new PDO('mysql:host=ip1;dbname=db1','root', '123456');
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
string2:
try {
$conn2 = new PDO('mysql:host=ip2;dbname=db2','root', '123456');
$conn2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
i using join query for join tb1 to tb2:
$stmt = $conn1->prepare(" select db1.*,db2.col1 from db1 left join db2 on db1.col1=db2.col2");
$stmt -> execute();
$result=$stmt->fetchAll();
if(count($result)){
foreach($result as $row){
echo $row[col1]";
}}
else{
Echo 'Not rows';
}
}
catch(PDOException $e){
echo $e->getMessage();
}
It not work.
i have tried $stmt = $conn1,$conn2-> prepare... and it not work too. i wrong something?
You did't mentioned Tables name in your join statement. I think you may want to do something like this :
SELECT * FROM db1.table_name as d1 LEFT JOIN db2.table_name as d2
ON d1.col1 = d2.col2
Try to replace your real Tables name with table_name in db1 and db2 in above statement.
I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);