I am trying to insert an array of values multiple times into a table.
I have a simple array that is generated by a user checking a box and that's what gets added to the array, I then want to insert each value into a table, I thought I could do it with a foreach loop and iterate $i but it appears I can't, I don't need to worry about security or anything as this is internally used by two people.
here is what I have:
foreach($detailsinvoice as $desc){
$conn3 = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql3 = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
$st3 = $conn3->prepare ( $sql3 );
$st3->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st3->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st3->execute();
$this->InvoiceNumber = $conn3->lastInsertId();
$conn3 = null;
}
This was my first attempt but gathered that the connection can only be used once then exits, so I tried an iteration but again I learnt that you can't do that with the PDO statement.
$i = 3;
foreach($detailsinvoice as $desc){
$conn[$i] = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql[$i] = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
$st[$i] = $conn[$i]->prepare ( $sql[$i] );
$st[$i]->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st[$i]->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st[$i]->execute();
$this->InvoiceNumber = $conn[$i]->lastInsertId();
$conn[$i] = null;
$i++;
}
detailsinvoice is the array and the ContactName will be the same each time (the Contactname works just need to figure out looping the array)
I would appreciate if someone could point me in the right direction.
Feature of prepared statements is that you can prepare a statement once and then execute it multiple times, so your code can be rewritten as:
// Create a connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
// Create a statement
$st = $conn->prepare ($sql);
foreach ($detailsinvoice as $desc) {
// bind values and execute statement in a loop:
$st->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st->execute();
$this->InvoiceNumber = $conn->lastInsertId();
}
// this is optional
$conn = null;
I have no idea where you got the idea a connection can only be used once from. You should connect only once in a script. Then as long as you store and pass around the $conn variable to any functions you may use (Scope of course is relevant here) you can use it as many times as you like.
// connect ONCE per script
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// write the query once
$sql = "INSERT INTO xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
// and prepare it once.
$st = $conn->prepare ( $sql );
// now loop over the array of parameters any number of times you like
foreach($detailsinvoice as $desc){
$st->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st->execute();
// this line looks wrong, as $this->InvoiceNumber will get overwritten
// each time round the loop
//$this->InvoiceNumber = $conn->lastInsertId();
// maybe you ment this, so at least you would have them all????
$this->InvoiceNumber[] = $conn->lastInsertId();
// or I have to assume you are going to add another query HERE
// that will use that ID
}
The concept of a prepared statement is that it is passed to the database, compiled, optimised and saved in the database almost like a stored proceedure.
Once prepared it can be used again and again. All you do is put new values into your parameters each time you execute it.
Related
I asked a question about the best way, performace-wise, to make multiple inserts( hundreds or even thousands) in prepared statements. See here for it How to perform multiple MySQL inserts in PHP.
In the course of answering the question, this old issue came up again : Do multiple SQL calls really take place in the following or not? :
$stmt = $dbLink->prepare( "INSERT INTO table SET id = :ID,
name = :name,
email = :email,
mobile = :mobile");
$stmt->bindParam( ':ID', $person->getID(), PDO::PARAM_STR );
$stmt->bindParam( ':name', $person->getName(), PDO::PARAM_STR );
$stmt->bindParam( ':email', $person->getEmail(), PDO::PARAM_STR );
$stmt->bindParam( ':mobile', $person->getMobile(), PDO::PARAM_STR );
foreach( $persons as $person ){
$stmt->execute();
}
Please, I think something like this cannot be right and wrong at the same time. There has to be a fact about it; and I just don't know that fact.
First, you should re-order your code a bit:
the $person is not defined outside the loop (or is not what you think), so you will get warnings, and the bindParam will set empty values
you will be inserting the same (empty) values in your for loop, since you never update the query parameters.
Do it like this, as was explained in this answer:
$stmt = $dbLink->prepare( "INSERT INTO table SET id = :ID,
name = :name,
email = :email,
mobile = :mobile");
foreach ( $persons as $person ) {
$stmt->bindParam( ':ID', $person->getID(), PDO::PARAM_STR );
$stmt->bindParam( ':name', $person->getName(), PDO::PARAM_STR );
$stmt->bindParam( ':email', $person->getEmail(), PDO::PARAM_STR );
$stmt->bindParam( ':mobile', $person->getMobile(), PDO::PARAM_STR );
$stmt->execute();
}
Second, every time you run $stmt->execute() you are executing a query. Therefore, you will run count( $persons ) queries. The prepared statement is a little bit faster, because the SQL query string only has to be parsed once.
This will run pretty fast, even for thousands of records. However, you may get a delay every time the database writes to disk; this is especially noticable with software RAID and slow disks. You can eliminate all but one of those delays by using transactions:
$dbLink->beginTransaction();
$stmt = $dbLink->prepare( ..... );
foreach ( $persons as $person ) {
...bindParam();
...execute();
}
$dbLink->commit();
I'm pretty new to PHP and PDO and I'm trying to make a simple login system. Now, I'm trying to fetch the id and password from my table to compare with the password that the user input(I'm using one way encryption with salt). So, now the problem is, when I do $password = $stmt->fetchColumn(1) only, my login system works. Now when I try to get the id by doing $id = $stmt->fetchColumn(0) just before $password, I cannot login anymore and I get my "Wrong Username/Password" error.
Now I'm pretty sure that I'm doing something wrong with the fetchColumn but I can't figure it out.
Here's a code snippet that works:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$password = $stmt->fetchColumn(1);
Now the following doesn't work. Notice that this happens when I added the $id:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$id = $stmt->fetchColumn(0); //That's the problem
$password = $stmt->fetchColumn(1);
Any help is greatly appreciated.
From the documentation:
PDOStatement::fetchColumn — Returns a single column from the next row of a result set
Each time you call fetchColumn it advances to the next row of the result set.
Try using PDOStatement::fetch instead to fetch the entire row as an an array and then accessing the values from there.
$stmt->execute();
$row = $stmt->fetch();
$id = $row[0];
$password = $row[1];
I'm about to commence building a site using mssql and php.
I plan to use PDO's, however, as I currenlty believe its not possible to use named parameters.
Currently in MySQL I would use named placeholders in my query as such;
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *
FROM table
LIMIT :numRows";
$st = $this->conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
However when using MSSQL;
$conn = new PDO("mysql:host=" . DB_HOST .";dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
$sSQLInsert = "SELECT TOP ? *
FROM table";
$aParams = array($iLimit);
$st = sqlsrv_query($dbhandle, $sSQLInsert, $aParams)){}
My worry appears when I have many parameters that need to be bound. Managing the order of them and dancing back and forth between query-parameters doesnt seem ideal.
So my question; is it posible to use named placeholders with MSSQL?
This would be a simple script to write an check, however I found documentation and an example! The answer is YES! Name parameters works with PDO_MSSQL.
https://msdn.microsoft.com/en-us/library/ff628166(v=sql.105).aspx
$stmt = null;
$contact = "Sales Agent";
$stmt = $conn->prepare("select * from Person.ContactType where name = :contact");
$stmt->bindParam(':contact', $contact);
$contact = "Owner";
$stmt->execute();
No You cannot use named Placeholder with sqlsrv_ or any other extension.
This is a feature of PDO only.
I plan to use PDO's, however, as I currenlty believe its not possible
to use named parameters.
You can do it with SQL server:
$sql = "SELECT TOP :numRows *
FROM table";
$st = $this->conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
var_dump($st->fetch());
It is not about the server, it is more about the driver, this PDO advantage since it is compatible with most database. You don't have to change your code, just the connection.
You might have luck looking at the following PDF (auto download of pdf):
http://tinyurl.com/orc2xkc
It has examples binding with variables and arrays.
$sql = ‘select Title,
FirstName,
MiddleName,
LastName
from SalesLT.Customer
where Title = :title and CustomerId<10’;
$query = $conn->prepare($sql);
$title = ‘Mr.’;
$query->bindParam(‘:title’, $title);
$query->execute();
In the meantime I will look up info on mssql driver to use because that apparently plays into it.
Edit ... As for the driver look at the comments under this question:
From PDO to SQLSRV
Many thanks for all the replies to this. After some time I've managed to get it working, so in answer to my question; Yes it is possible to use Named Placeholders with MSSQL.
After installing the SQLSRV PDO extension, placeholders can be used as such;
$database = "";
$server = "";
$conn = new PDO( "sqlsrv:server=$server ; Database = $database", DB_USER, DB_PASSWORD);
$sql = "SELECT * FROM Table WHERE MemberID =:MemberID";
$iMemberID = 5;
$st = $conn->prepare($sql);
//named placeholders within the execute() as an array.
$st->execute(array(':MemberID'=>$iMemberID));
//OR using bind param..
$st->bindParam(':MemberID', $iMemberID);
while ($row = $st->fetch()){
echo "<pre>";
var_dump($row);
echo "</pre>";
}
Thanks to Drew Pierce for the link to the drivers and pdf and everyone else for the help.
Following is the code in my script. the $sql statement is properly working when executed in phpmyadmin. But it dosent work in the following code. displaying only one row of data.
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql="SELECT DISTINCT productId FROM bid WHERE userId =:id";
$st = $conn->prepare( $sql );
$st->bindParam( ":id", $_SESSION['id'], PDO::PARAM_INT );
$st->execute();
$data=$st->fetch(PDO::FETCH_ASSOC);
$conn=null;
print_r($data);
In both methods, replace
$data = $st->fetch(PDO::FETCH_ASSOC);
with the code given.
One of the method would be:
$data = $st->fetchAll(PDO::FETCH_ASSOC);
Loop
while( $data = $st->fetch(PDO::FETCH_ASSOC) )
print_r($data);
$conn=null;
I'm trying to use a LIKE statement to search through a number of columns.
The following code gives the wanted result:
$zoek='%'.$_GET['zoek'].'%';
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//insert the user:
$sql = "SELECT `leerlingnr`,`voornaam`,`achternm_tsnvoegsels`,`klas`
FROM `roosters`
WHERE `leerlingnr` LIKE '$zoek'
OR `voornaam` LIKE '$zoek'
OR `achternm_tsnvoegsels` LIKE '$zoek'
OR `klas` LIKE '$zoek'";
$st = $conn->prepare ( $sql );
$st->execute();
var_dump ( $st -> fetchAll ( ) ) ;
$conn = null;//sluit de connectie
However, when I try to bind the $zoek value, instead of just inserting it in the query, I get 0 results.
$zoek='%'.$_GET['zoek'].'%';
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//insert the user:
$sql = "SELECT `leerlingnr`,`voornaam`,`achternm_tsnvoegsels`,`klas`
FROM `roosters`
WHERE `leerlingnr` LIKE ':zoekterm1'
OR `voornaam` LIKE ':zoekterm2'
OR `achternm_tsnvoegsels` LIKE ':zoekterm3'
OR `klas` LIKE ':zoekterm4'";
$st = $conn->prepare ( $sql );
$st->bindValue( ':zoekterm1', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm2', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm3', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm4', $zoek, PDO::PARAM_STR);
$st->execute();
var_dump ( $st -> fetchAll ( ) ) ;
$conn = null;//sluit de connectie
After trying for about half an hour (I fixed having % in the query and having only one :zoekterm), I really don't see what I've done wrong.
When binding variables, don't use quotes.