Create foreach for a value that exists twice - php

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
}

Related

Using PHP and MySQL, how do you send a variable into a WHERE... IN clause?

The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}

Add try to pdo execute

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
}

how to know if the SQL query PDO is empty?

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 is on a occasion, only part of a record inserted?

The problem I am having is on occasion (1 of every 8 or so) insertions to the database, the string value of (fileLocation) will be incomplete. so for example..
what should be "filecomplete.mp4" will be inserted as "filecomple".
Has anyone experienced this before or have any ideas as to what the problem could be?
Here is my insert statement.
public function addNewGame($gameID, $receiverID, $senderID, $gameTrack, $fileLocation){
$this->gameid = $gameID;
$this->receiverid = $receiverID;
$this->senderid = $senderID;
$this->gameTrack = $gameTrack;
$this->filelocation = $fileLocation;
$SQUERY = "SELECT GameId FROM ActiveGames WHERE GameId = :gameid";
try{
$stamt = $this->connection->prepare($SQUERY);
if ($stamt === false) {
throw new Exception($this->connection->error);
}
$stamt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stamt->execute();
$result = $stamt->fetchAll();
$resultCount = count($result);
if($resultCount > 0){
echo "existing record";
} else{
$QUERY = "INSERT INTO ActiveGames (GameId,
ReceiverId,
SenderId,
GameTrack,
FileLocation)
VALUES (
:gameid,
:receiverid,
:senderid,
:gametrack,
:filelocation)";
try{
$stmt = $this->connection->prepare($QUERY);
if ($stmt === false) {
throw new Exception($this->connection->error);
}
$stmt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stmt->bindValue(':receiverid', $this->receiverid, PDO::PARAM_INT);
$stmt->bindValue(':senderid', $this->senderid, PDO::PARAM_INT);
$stmt->bindValue(':gametrack', $this->gameTrack, PDO::PARAM_STR);
$stmt->bindValue(':filelocation', $this->filelocation, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
}
catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}

display comments under each image

I want to display all the comments posted under each image from a database.
I tried the following code, but I was able to get only one comment, which was the last one posted.
$sql1="SELECT user,comment FROM comment_table where imagename=:file";
$q1=array(':file'=>$file);
try {
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
$c = $result["comment"];
$u=$result["user"];
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
echo "<tr><td>".$u.":".$c."</td><tr>";
Please help needed and appreciated.
You need to create a foreach to print all the comments. Take a read here http://php.net/manual/en/control-structures.foreach.php
With your code it just shows one comment, so try this:
$sql1="SELECT user,comment FROM comment_table where imagename=:file";
$q1=array(':file'=>$file);
try {
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
foreach ($result as $res) {
echo "<tr><td>".$res["user"].":".$res["comment"]."</td><tr>";
}

Categories