PDO Insert Array Into Table - mysql

Hi experienced people :)
Can someone help me determine why the following PDO MYSQL statement is only inserting a single row into the table when there are more than 1 value in the array?
$availability array values = "1,2,4" for example.
$stmt =$con -> prepare ("INSERT INTO Availability (Periods_P_ID, Users_user_id) VALUES (:period, $user_id)");
foreach($availability as $periods){
$stmt -> bindParam(':period', $periods, PDO::PARAM_INT);
}
$stmt -> execute();

You only need to bind the parameter once, outside the loop. But you need to call execute() in the loop to insert each row.
$stmt =$con -> prepare ("INSERT INTO Availability (Periods_P_ID, Users_user_id) VALUES (:period, :user_id)");
$stmt->bindParam(':period', $periods, PDO::PARAM_INT);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
foreach($availability as $periods){
$stmt -> execute();
}

Related

UPDATE with CASE Statements using a similar foreign key

I am trying to update a database that tracks a household. It keeps the household head as a client in a separate table, but uses their ID as a foreign key in the household table. I need to be able to add multiple people in a household. I tried using just an UPDATE statement, but it only replaced the data when I tried to add multiple people at once. I am trying to do this not using DELETE and INSERT statements for fear of losing information. For added information, this is all manipulated by a PHP Fat-Free Website because my school teaches it.
function editHousehold($id, $name, $age, $gender){
$id = $this->getLastId();
$sql= "UPDATE Household SET `name`=:name, age=:age, gender=:gender WHERE
Guests_ClientId=:Guests_ClientId";
$statement = $this->dbh->prepare($sql);
$statement->bindParam(':name', $name, PDO::PARAM_STR);
$statement->bindParam(':age', $age, PDO::PARAM_STR);
$statement->bindParam(':gender', $gender, PDO::PARAM_STR);
$statement->bindParam(':Guests_ClientId', $id, PDO::PARAM_INT);
$statement->execute();
}
Vs.
function editNeeds($id,$resource,$date, $amount, $voucher, $checkNum){
$sql = "DELETE FROM Needs WHERE Guests_ClientId = $id";
$statement = $this->dbh->prepare($sql);
$statement->execute();
$id = $this->getLastId();
$sql= "INSERT INTO Needs (resource, visitDate, amount, voucher, checkNum, Guests_ClientId)
VALUES (:resource, :date , :amount, :voucher, :checkNum, $id)";
$statement = $this->dbh->prepare($sql);
$statement->bindParam(':resource', $resource, PDO::PARAM_STR);
$statement->bindParam(':amount', $amount, PDO::PARAM_STR);
$statement->bindParam(':voucher', $voucher, PDO::PARAM_STR);
$statement->bindParam(':checkNum', $checkNum, PDO::PARAM_STR);
$statement->bindParam(':date', $date, PDO::PARAM_STR);
$statement->execute();
}
/**
* edit households, removes the old and replaces witha new set of values
* #param $id
* #param $name
* #param $age
* #param $gender
*/
function editHousehold($id, $name, $age, $gender){
$sql = "DELETE FROM Household WHERE Guests_ClientId = $id";
$statement = $this->dbh->prepare($sql);
$statement->execute();
$id = $this->getLastId();
$sql= "INSERT INTO Household (name, age, gender,Guests_ClientId)
VALUES (:name,:age,:gender,$id)";
$statement = $this->dbh->prepare($sql);
$statement->bindParam(':name', $name, PDO::PARAM_STR);
$statement->bindParam(':age', $age, PDO::PARAM_STR);
$statement->bindParam(':gender', $gender, PDO::PARAM_STR);
$statement->execute();
}
I think you are looking for an "either insert new entry or update if the primary key exists" type of statement. This is called "upsert", and MySQL provides it in the form of INSERT ... ON DUPLICATE KEY UPDATE.
It will insert new entries, unless the primary key of one of the entries to insert already exists. If so, it will instead update the existing entry.

Perl DBI how to prepare single insert multiple rows

I am inserting multiple rows in a table with single insert query using the following format:
INSERT INTO $table (field1,field2) VALUES (value1,value2),(values3,values4);
The number of rows varies. Is there a way to use Perl's prepare statement for this kind of queries ?
For example, if I am inserting only one row I can do like the below:
$query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
$sth = $dbh->prepare($query);
$sth->execute('value1','value2');
However, I want to do something like the below:
$values = '(value1,value2),(values3,values4),(values5,values6)';
$query = "INSERT INTO $table (field1,field2) VALUES ?";
$sth = $dbh->prepare($query);
$sth->execute($values);
Is this possible? or any other ways to achieve this ?
You can build up a query that can do what you want. Assuming that your records are in an array like this.
my #records = ( ['value1', 'value2'], ...) ;
Then you can create a query dynamically and execute it.
my $values = join ", ", ("( ?, ? )") x #records;
my $query = "INSERT INTO $table (field1,field2) VALUES $values";
my $sth = $dbh->prepare($query);
$sth->execute(map { #$_ } #$records);
Also in your example you are using string interpolation on the table name. Be careful with that as it can lead to database injections.
Put each record in its own array, then make an array of those:
my #records = ( [ 'value1', 'value2' ], [ 'value3', 'value4' ], [ 'value5', 'value6' ] );
Then prepare your INSERT statement:
my $query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
my $sth = $dbh->prepare($query);
Then loop over your records and execute your statement handle for each one:
foreach my $rec ( #records ) {
$sth->execute( #$rec );
}

PDO prepared statement with insertion in database

Please i have this quetion,
I have here:
$query = $db->prepare('Update survey_content set '.$type.' = '.$type.'+1 where id = '.$where);
$query->execute();
I'm new to PDO and i really don't know how to create a new query, i need to add a record on the database, is it ok like this?
$query1 = $db->prepare('INSERT INTO daily (selected)
VALUES (.$type.)');
$query1->execute();
Use a placeholder and fill the value in the execute method
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (?)");
$query1->execute($selected_data);
or bind the parameter seperately
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (:sel_dat)");
$query1->bindParam(":sel_dat",$selected_data);
$query1->execute();

Mysql select and insert using prepared statement

My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select
What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php
You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();
Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm

using an ID before it is created sql?

Hi i have a question about mysql
this is my query:
$geboortedatum = $_POST['dag'].'-'.$_POST['maand'].'-'.$_POST['jaar'];
$geboortedatum1 = $_POST['dag1'].'-'.$_POST['maand1'].'-'.$_POST['jaar1'];
try{
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
INSERT INTO clienten
(client_voornaam,
client_achternaam,
client_geboortedatum,
client_geslacht,
client_adres,
client_postcode,
client_woonplaats,
client_contactpersoon,
client_diagnose,
datun_aanmaak)
VALUES (:voornaam,
:achternaam.
:geboortedatum,
:geslacht,
:adres,
:postcode,
:woonplaats,
:contactpersoon,
:diagnose,
:datumaanmaak)
INSERT INTO verzorgers(
wat_is_verzorger,
voornaam_verzorger,
achternaam_verzorger,
geboortedatum_verzorger,
email_verzorger,
geslacht_verzorger,
adres_verzorger,
postcode_verzorger,
woontplaats_verzorger,
tel1_verzorger,
tel2_verzorger,
datum_aanmaak
)
VALUES(
:watisverz
:voornaamverz,
:achternaamverz,
:geboortedatumverz,
:emailverz,
:geslachtverz:
:adresverz,
:postcodeverz,
:woonplaatsverz,
:tel1verz,
:tel2verz,
:datumaanmaak
)
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':voornaam', $_POST['voornaam'], PDO::PARAM_STR);
$stmt->bindParam(':achternaam', $_POST['achternaam'], PDO::PARAM_STR);
$stmt->bindParam(':geboortedatum', $geboortedatum, PDO::PARAM_INT);
$stmt->bindParam(':geslacht', $_POST['geslacht'], PDO::PARAM_STR);
$stmt->bindParam(':adres', $_POST['adres'], PDO::PARAM_STR);
$stmt->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
$stmt->bindParam(':woonplaats', $_POST['woonplaats'], PDO::PARAM_STR);
$stmt->bindParam(':contactpersoon', $_POST['contactpersoon'], PDO::PARAM_STR);
$stmt->bindParam(':diagnose', $_POST['diagnose'], PDO::PARAM_INT);
$stmt->bindParam(':datumaanmaak', $_POST['datum_toetreding'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo '<pre>';
echo 'Regel: '.$e->getLine().'<br>';
echo 'Bestand: '.$e->getFile().'<br>';
echo 'Foutmelding: '.$e->getMessage();
echo '</pre>';
} ?>
Now when the client and verzorger are created, they both get an unique ID.
Client had a column that stores the verzorger ID associated and vica versa.
Is it possible to make a query that also directly stores the IDs created?
EDIT:
ok maybe to difficult, maybe an answer to get only the client id in verzorger?:)
How about something like this (TableAID and TableBID are both AUTO_INCREMENT columns):
INSERT INTO TableA
(SomeColumn)
VALUES
('Blah');
SET #TableAID = LAST_INSERT_ID();
INSERT INTO TableB
(TableAID, AnotherColumn)
VALUES
(#TableAID,'Foobar');
SET #TableBID = LAST_INSERT_ID();
UPDATE TableA
SET TableBID = #TableBID
WHERE TableAID = #TableAID;
What you can do is create a function that queries against a sequence generator:
create function foo returns int
Begin
Declare nextValue int
Set nextValue = SELECT NEXT VALUE FOR mySequence;
End
return (nextValue);
Which would allow you to pass around the value returned from this sequence and you could know "ahead" of time what the values were going to be.
EDIT
Please understand how concurrency works and use either pessimistic or optimistic locking. While this should be obvious, some feel as though it is necessary to include.