This is a code to update a table with foreach loop. But it update the last value three times which is POST[s3_name]
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
You could get the id from somewhere and loop that as well. Something like this
$names = [
['id' => 1, 'name' => 'name1'],
['id' => 2, 'name' => 'name2'],
['id' => 3, 'name' => 'name3']
];
foreach ($names as $name) {
try {
$query = "update students SET Name=:Name WHERE ProjectID=:Id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name['name']);
$stmt->bindParam(':Id', $name['id']);
$result = $stmt->execute();
$msg = "Record updated";
} catch(PDOException $ex) {
$msg = $ex -> getMessage();
}
}
Related
I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
) SELECT LAST_INSERT_ID();
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id_category = $result["id"];
"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - #barell
Try this;
<?php
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
)
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//$id_category = $result["id"];
$id_category = $db->lastInsertId();
Hope it helps
I have tables like this:
-artists
-djs
-track_artist
-track_dj
I am adding two or more artists/djs while adding song via multiple select box. But I couldn't find how to edit those rows.
Adding song function:
$sql = "INSERT INTO sarki (sarki_isim, sarki_tarz, sarki_file, sarki_resim, sarki_eklenmetarihi) VALUES (:isim, :tarz, :file, :resim, NOW())";
$sqlartist = "INSERT INTO trackartist (trackartist_artist, trackartist_track) VALUES (:artistid, :trackid)";
$sqldj = "INSERT INTO trackdj (trackdj_dj, trackdj_track) VALUES (:djid, :trackid)";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':isim' => $b["isim"], ':tarz' => $b["tarz"], ':file' => $b["file"], ':resim' => $b["resim"]));
$trackid = $this->db->lastInsertId();
foreach ($b["artists"] as $artist) {
$insert = $this->db->prepare($sqlartist);
$insert->execute(array(":artistid" => $artist, ":trackid" => $trackid));
}
foreach ($b["djs"] as $artist) {
$insert = $this->db->prepare($sqldj);
$insert->execute(array(":djid" => $artist, ":trackid" => $trackid));
}
$db = null;
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
I have an array like:
$arrays = array(
array('id' => '1','Name' => 'Monica','online' => '1'),
array('id' => '2','Name' => 'Jessica','online' => '1')
);
I only included 2, but let's say I have 200 of these. I already have a table in SQL with associated columns id, name and online.
Can you help me input these into database? I'm developing using wordpress. From Insert array into MySQL database with PHP I have an idea of how to do it for 1 single array
If you're having an array , you need to use a foreach loop to know the length content of insertion.
This is an example of insertion:
if(is_array($array)){
$sql = "INSERT INTO some_table (id, name, online) values ";
$valuesArr = array();
foreach($array as $row){
$id= (int) $row['id'];
$email = mysql_real_escape_string( $row['name'] );
$name = mysql_real_escape_string( $row['online'] );
$valuesArr[] = "('$id', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
Please try this.
Using PDO example
$sql = <<<EOT
INSERT IGNORE INTO
table_name (id, name, online)
VALUES
(:id, :name, :online)
;
EOT;
define("INSERT_UPDATE_SQL", $sql,true);
try{
$con = new PDO(CONNECTION_STRING);
if(is_array($arrays)){
$stmt = $con->prepare(INSERT_UPDATE_SQL);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':online', $online);
foreach($arrays as $row){
$id = (int)$row['id'];
$name = $row['Name'];
$online = $row['online'];
$stmt->execute();
}
$stmt = null;
}
$con = null;
}catch (PDOException $e) {
echo 'error !!';
throw $e;
}
not changed if already registered.
I add a lot a values with params ($queryArr) in INSERT statemnt in foreach
public function getClients()
{
helper::putToLog("\n----- getClients\n", true);
$managedCustomerService = $this->user->GetService('ManagedCustomerService', ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array("CustomerId", "Name", "CurrencyCode");
$graph = $managedCustomerService->get($selector);
if (isset($graph->entries)) {
$accounts = [];
foreach ($graph->entries as $account) {
$accounts[$account->customerId] = $account;
}
helper::putToLog('Clients found: '.count($accounts)."\n", true);
} else {
helper::putToLog('Clients not found'."\n", true);
return false;
}
$sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
$sth->execute();
$sth = null;
$queryClients = "INSERT INTO `adwords_clients_google` (`client_foreign_id`, `status`, `client_name`, `client_currency`) VALUES";
foreach($accounts as $account) {
$queryArr[$account->customerId] = "(".$account->customerId.", 1, :".$account->customerId.", :".$account->customerId."_currencyCode)";
$nameArr[$account->customerId] = $account->name;
$currencyArr[$account->customerId."_currencyCode"] = $account->currencyCode;
}
$queryClients .= implode(',', $queryArr) . " ON DUPLICATE KEY UPDATE `status` = VALUES(`status`), `client_name` = VALUES(`client_name`) ";
$sth = $this->db->prepare($queryClients);
foreach ($nameArr as $key => $value) {
$sth->bindValue(":$key", str_replace("'", "\'", $value), PDO::PARAM_STR);
}
foreach ($currencyArr as $key => $value) {
$sth->bindValue(":$key", $value, PDO::PARAM_STR);
}
print_r($sth);
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);
}
return true;
}
and there are 2 array of values I need to bind $nameArr and $currencyArr. I didn't get any errors but column client_currency is empty even though array $currencyArr contains all necessary values. What's wrong?
It looks like you haven't grasped the concept of prepared+paramterized statements yet.
You prepare them once and then execute them with varying parameters (one or) multiple times.
$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`)
');
$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();
}
if you haven't got any error message/log entries please make sure that the error handling mode of your PDO instance really is set to PDO::ERRMODE_EXCEPTION.
edit: to illustrate that, here's an sscce:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo); // creating temporary table + sample data for this example
printTable("before", $pdo);
$sth = $pdo->prepare('
INSERT INTO
`soFoo`
(`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`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
$accounts = data();
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
printTable("after", $pdo);
function data() {
return array_map(function($e) { return (object)$e; }, array(
array('customerId'=>1, 'name'=>'customerA', 'currencyCode'=>'cA'),
array('customerId'=>2, 'name'=>'customerB', 'currencyCode'=>'cB'),
));
}
function printTable($cap, $pdo) {
echo $cap, "\r\n";
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $r ) {
echo join(', ', $r), "\r\n";
}
}
function setup($pdo) {
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
client_foreign_id int,
`status` int,
client_name varchar(32),
client_currency varchar(32),
unique(client_foreign_id)
)
');
$pdo->exec("INSERT INTO soFoo (client_foreign_id,status,client_name,client_currency) VALUES (1, 0, 'agent smith', 'kruegerrand')");
}
prints
before
1, 0, agent smith, kruegerrand
after
1, 1, customerA, kruegerrand
2, 1, customerB, cB
I'm using php to connect to mysql database and am using the following function to retrieve multiple rows from database and then add them to an array and send them back. I'm getting internal server error or 500x error messages. I'm not sure what is wrong with this code. I've tried to figure it out but can't get it.
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
if ($stmt->execute()) {
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$resp = array();
while($stmt->fetch()){
$row = array();
array_push($row, $col1, $col2, $col3);
array_push($resp, $row);
}
$msg = array('msgid' => $msgid,'title' => $title,'fromuname' => $fromuname);
$stmt->close();
return $msg;
} else {
$stmt->close();
return NULL;
}
}
how should I go about doing this? The function that handles the returned results are as follows
$app->get('/inbox', 'authenticate', function() use ($app){
ob_start("ob_gzhandler");
global $global_user_name;
$db = new DbHandler();
$resp = $db->getUnreadMessages($global_user_name);
$msgs = array();
$msgs['status'] = 'success';
$msgs['version'] = 0.1;
array_push($msgs, $resp);
$app->response()->header('Content-Type', 'application/json');
echo json_encode($msgs);
exit;
});
The PDO method automating this is $stmt->fetchAll() :D
public function getUnreadMessages($uname)
{
$stmt = $this->conn->prepare("SELECT msgid,title,fromuname FROM messages WHERE touname = ? and status = ?");
$stmt->execute([$uname, 'unread']))
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Return false if nothing has been found or something like :
$msg = [
[
'msgid' => 2746,
'title' => 'Random title',
'fromuname' => 'SomeGuy'
],
[
'msgid' => 754,
'title' => 'Some title',
'fromuname' => 'Random Name'
],
[
'msgid' => 27686,
'title' => 'Unreadable title',
'fromuname' => 'Training dummies'
],
];
I've solved my question. It was that I was creating an array within a loop. This seems to be disallowed. Here's the code that did work in the end
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
$result = $stmt->execute();
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$outer = array();
$inner = array();
while($stmt->fetch()){
array_push($inner, $col1, $col2, $col3);
}
array_push($outer, $inner);
return $outer;
$stmt->close();
}