I have a array containing of 250 eight character code. I am trying to insert this array to the table tbl_coupon. This is code I tried which is inserting only 1 data to the database.
I couldnot figure out where I did mistake.
$db = new Connection();
$sql = $db->query('insert into tbl_coupon(code) values(:code)');
$db->beginTransaction();
try {
foreach ($coupons as $coupon) {
$db->bind(':code', $coupon);
}
$db->execute();
} catch (\Exception $e) {
echo $e->getMessage();
$db->cancelTransaction();
}
$db->endTransaction();
Call $db->execute(); inside the foreach loop. The bind() just "replaces" the placeholder, so it is 250 times replaced and only the last one is executed.
$db = new Connection();
$sql = $db->query('insert into tbl_coupon(code) values(:code)');
$db->beginTransaction();
try {
foreach ($coupons as $coupon) {
$db->bind(':code', $coupon);
$db->execute();
}
} catch (\Exception $e) {
echo $e->getMessage();
$db->cancelTransaction();
}
$db->endTransaction();
$db->execute();
Place this line inside for loop. You are binding the values inside for loop, the values will be binded to the statement and replaced till the last element in the array.
Then after completion of for loop you are calling $db->execute(), this will store only the last value of your array to the table
Related
So I'm new to PHP/PDO and I'm having some problems with passing the fetched variable on to the second statement. I'm also having problems with exceptions i don't know how the right structure for this situation.
try {
$connection->beginTransaction();
$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);
while($row = $stmt->fetch()){
echo $physicalexamid_insert=$row['physicalexamid'];
/* I need to use this data for another try and catch or sql statements for example*/
$count_physical_exam_id = count($physical_exam_id);
for ($x=0; $x < $count_physical_exam_id; $x++) {
if (!(empty($physical_exam_id[$x]))) {
try {
$connection->beginTransaction();
$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_dtl(?,?,?,?,?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,1,PDO::PARAM_INT);
$stmt->bindValue(3,$physical_exam_id[$x],PDO::PARAM_INT);
$stmt->bindValue(4,$physical_exam_desc[$x],PDO::PARAM_STR);
$stmt->bindValue(5,$normal[$x],PDO::PARAM_INT);
$stmt->bindValue(6,$undone[$x],PDO::PARAM_INT);
$stmt->bindValue(7,$specific[$x],PDO::PARAM_INT);
$stmt->execute();
$connection->commit();
} catch(PDOException $ex) {
//$connection->rollBack();
echo $ex->getMessage();
}
}
}
}
$stmt->execute();
$connection->commit();
} catch(PDOException $ex) {
$connection->rollBack();
echo $ex->getMessage();
Can someone help me with this? Thanks.
There's a couple of issues with your code:
You're not executing the first statement before you call fetch on it.
You're over-writing the $stmt variable in your loop.
The opening section of your code should be like this:
$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);
$stmt->execute();
Once you've done that you can loop through with a control statement like you're doing (e.g. while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ... }).
Inside that control structure, instead of using the variable $stmt for a new (second) statement, use something like $stmt2 or $inner_stmt, so that you don't over-write the outer variable.
I'd like to execute some queries that doesn't return result set, and then execute a real query, and fetch its result.
Here is an exemple that doesn't work :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1;";
$db->exec($query);
$query = "select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
This code neither doesn't work :
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1; select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
But this code works :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "select 1;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
Thanks for your help
I know this is old, but for other people finding this from Google: you need to use PDOStatement::nextRowset to iterate over the result sets from your multiple queries.
However, it seems there are memory issues when using nextRowset with dblib in some versions (it tried to allocate 94Tb in my case...), so I ended up re-engineering to avoid multiple SQL queries altogether (instead duplicating the value of the DECLARE where it was being used).
PDO::query docs (http://php.net/manual/it/pdo.query.php) say
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
This could mean that you can execute with query() both queries with and without result
function get_grade($sku) {
require("config.php");
try {
$results = $db -> query prepare ("SELECT name, subject1,grade1,attendance,gender,subject2,grade2,subject3,grade3 FROM student WHERE sku = ?"); //binds the sku to the question mark
$results -> bindParam;
$results -> execute();
}
catch exception ($e) {
echo "could not connect";
exit;
}
$product = $results-> fetch (PDO::FETCH_ASOC);
}
How to get a where clause to work, where if the user has the same or similar attendance, subjects and grades then they will get then they will get that grade from a past student.
You need to bind $sku:
$results->bindParam(1, $sku);
This should work for you:
function get_grade($sku) {
require("config.php");
try {
$results = $db->prepare("SELECT name, subject1,grade1,attendance,gender,subject2,grade2,subject3,grade3 FROM student WHERE sku = :sku");
//^^^^^^^^Perpare statement here //^^^^Placeholder for variable
$results->execute(array("sku" => $sku));
//^^^^^^^^^^^^^^^^^^^Instead of binParam
} catch (PDOException $e) {
//^^^^^^^^^^^^^^^ Catch PDO exeption
echo $e->getMessage();
exit;
}
$product = $results->fetch(PDO::FETCH_ASOC);
}
Hey guys im having a little trouble with the PDO in php as the error it is returning is an undefined index. The code for the function and query and return of result is this:
function getUserDetails($user) {
$db = connect();
try {
$stmt = $db->prepare('SELECT name,addr AS address,team
FROM TreasureHunt.Player LEFT OUTER JOIN TreasureHunt.MemberOf ON (name=player)
LEFT OUTER JOIN TreasureHunt.PlayerStats USING (player)
WHERE name=:user');
$stmt->bindValue(':user', $user, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll();
$stmt->closeCursor();
} catch (PDOException $e) {
print "Error : " . $e->getMessage();
die();
}
return $results;
}
However when running the code for the index page i get an error that says Notice: Undefined index: name
The Code for the index is this:
try {
$details = getUserDetails($_SESSION['player']);
echo '<h2>Name</h2> ',$details['name'];
echo '<h2>Address</h2>',$details['address'];
echo '<h2>Current team</h2>',$details['team'];
echo '<h2>Hunts played</h2> ',$details['nhunts'];
echo '<h2>Badges</h2>';
foreach($details['badges'] as $badge) {
echo '<span class="badge" title="',$badge['desc'],'">',$badge['name'],'</span><br />';
}
} catch (Exception $e) {
echo 'Cannot get user details';
}
my question is why is it throwing a notice and how do i go around this problem?
fetchAll returns all results (potentially multiple rows) in a multidimensional array:
array(
0 => array(/* first row */),
1 => array(/* second row */),
...
)
That's why the array doesn't have a direct index 'name', it needs to be [0]['name'].
Or you shouldn't fetchAll, just fetch.
What is the best way to select a range of ids from one table and then put them
through a transaction loop to process a update one record at a time?
$result = mysql_query('SELECT p_code FROM replenishment ');
$ids = array();
while ($p_code = mysql_fetch_row($result)) {
$ids[] = $p_code[0];
foreach($ids as $p_code) {
mysql_query('SELECT #A:=replenishment.p_code,#B:=replenishment.model
from replenishment
left join replenishment1 on replenishment1.p_code = replenishment.p_code
where replenishment.branch=10
and replenishment.p_code=$p_code
and replenishment.stock < min
and replenishment1.stock > 0
group by replenishment.p_code');
mysql_query('UPDATE replenishment1
SET stock = (stock - #B), B5=(b5+#B) WHERE #A = replenishment1.p_code
and replenishment1.stock >= #B');
$row = mysql_fetch_assoc();
}
}
Start using PDO or MySQLi.
Through this you can manage your transaction and make sure that data enters in your database safely.
<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
/* You can put your foreach loop over here or you can also do the entire process for single update. It's your choice */
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
It guarantees that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.