PHP MySql PDO Multiple insert doesn't work - php

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.

Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

Related

SQLSRV bind param thats in mysql

I'm trying to convert this mysql code to work using sqlsrv
$planeId = $_GET["pid"];
$conn = OpenCon();
$sql = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
$stmnt = $conn->prepare($sql);
$stmnt->bind_param("s", $planeId);
$stmnt->bind_result($id, $pid, $fullname, $tat, $date, $engine1, $engine2, $engine3, $engine4);
$stmnt->execute();
$theRows = Array();
while ( $stmnt->fetch() )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
$stmnt->close();
echo json_encode($theRows);
CloseCon($conn);
This I what I've done so far but I'm missing the bind-param function not sure how to implement that. Because the output keeps coming out like this
[{"id":"","pid":"","fullname":null,"tat":null,"date":null,"engine1":null,"engine2":null,"engine3":null,"engine4":null}]
Even though I know there's an entry in Microsoft DB
$planeId = $_GET["pid"];
$theRows = Array();
$conn = OpenCon();
$query = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
//$stmnt = $conn->prepare($query);
$stmnt = sqlsrv_prepare($conn, $query, array(&$planeId));
if (sqlsrv_execute($stmnt) === false){
die( print_r( sqlsrv_errors(), true));
}
else{
while ( sqlsrv_fetch($stmnt) )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
echo json_encode($theRows);
}
CloseCon($conn);

prepare($sql)->execute() works, but $statement->execute() not

If I use the following statement, my code is working well:
$statement = $this->pdo->prepare($sql)->execute();
But if I use the following statements, my code doesn't work:
$statement = $this->pdo->prepare($sql);
$statement->execute();
Does anyone have an idea, what I'm doing wrong or why this is so?
Here my complete code:
public function deleteUser($pid_user){
/* DESCRIPTION
* delete an user an all his data
*
* PARAMETERS
*
* EXAMPLE
* deleteUser();
*/
try {
//begin transaction
$this->pdo->beginTransaction();
//define all tables to delete all entries from the overgiven user id
//name = name of the table
//column = column to identify the users entries
$tables = array();
$tables[0]["name"] = "snsho_bittrex_apikey";
$tables[0]["column"] = "fk_user";
$tables[1]["name"] = "snsho_bittrex_balances";
$tables[1]["column"] = "fk_user";
$tables[2]["name"] = "snsho_bittrex_deposit_history";
$tables[2]["column"] = "fk_user";
$tables[3]["name"] = "snsho_bittrex_order_history";
$tables[3]["column"] = "fk_user";
$tables[4]["name"] = "snsho_bittrex_withdrawal_history";
$tables[4]["column"] = "fk_user";
$tables[5]["name"] = "snsho_user_settings";
$tables[5]["column"] = "fk_user";
$tables[6]["name"] = "snsho_user";
$tables[6]["column"] = "pid_user";
//do the queries
$sql = '';
foreach($tables as $key => $table){
$sql .= 'DELETE FROM ' . $table["name"] . ' WHERE ' . $table["column"] . ' = ' . $pid_user . ';';
}
//$statement = $this->pdo->prepare($sql)->execute();
$statement = $this->pdo->prepare($sql);
$statement->execute();
if($this->pdo->commit()){
echo "commited";
}else{
echo "commit failed";
}
return TRUE;
} catch (Exception $e) {
$this->adminMessages->setSingleError("Failed: " . $e->getMessage());
$this->pdo->rollBack();
return FALSE;
}
}
Try the execute without the assignment.
$this->pdo->prepare($sql)->execute();
This only returns a true or false.

Do not update with empty vars on UPDATE statement

I am trying to run an sql update but i dont want to update when the post vars that are empty.
Code that i run is :
require '../includes/db.php';
$settings_owner = ( isset($_POST[wb_owner_field]) ? $_POST[wb_owner_field] : false );
$settings_title = ( isset($_POST[wb_title_field]) ? $_POST[wb_title_field] : false );
$settings_description = ( isset($_POST[wb_descr_field]) ? $_POST[wb_descr_field] : false );
$settings_keywords = ( isset($_POST[wb_keywd_field]) ? $_POST[wb_keywd_field] : false );
$settings_id = ( isset($_POST[wb_id]) ? $_POST[wb_id] : false );
try {
$sql = "UPDATE Website SET website_owner = '$settings_owner', website_title = '$settings_title', website_description = '$settings_description', website_keywords = '$settings_keywords' WHERE _ID = '$settings_id' ";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
One way is to test the value in the UPDATE statement:
$sql = "UPDATE Website
SET website_owner = IF('$settings_owner' = '', website_owner, '$settings_owner'),
website_title = IF('$settings_title' = '', website_title, '$settings_title'),
website_description = IF('$settings_description' = '', website_description, '$settings_description'),
website_keywords = IF('$settings_keywords' = '', website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id' ";
Another way is to build the UPDATE statement dynamically.
$sets = array();
if ($settings_owner != '') {
$sets[] = "website_owner = '$settings_owner'";
}
if ($settings_title != '') {
$sets[] = "website_title = '$settings_title'";
}
...
if (!empty($sets)) {
$sql = "UPDATE Website SET " . implode(', ', $sets) . " WHERE _ID = '$settings_id'";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
I don't do much web programming, and haven't touched php in 10 years, but I work with MySQL daily and would imagine something like this would work:
UPDATE Website
SET website_owner = IF('$settings_owner'='', website_owner, '$settings_owner')
, website_title = IF('$settings_title'='',website_title, '$settings_title')
, website_description = IF('$settings_description'='',website_description, '$settings_description')
, website_keywords = IF('$settings_keywords'='',website_keywords, '$settings_keywords')
WHERE _ID = '$settings_id'
;

SQL statement in while loop

For some reason my SQL UPDATE statement is not working.
$con=mysqli_connect("localhost","admin","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$items = array();
$desc = array();
$price = array();
$quantity = array();
$p=0;
while($inventorynumber>$p)
{
$invid[$p] = $_POST['invid'.$p.''];
$items[$p] = $_POST['item'.$p.''];
$desc[$p] = $_POST['desc'.$p.''];
$price[$p] = $_POST['price'.$p.''];
$quantity[$p] = $_POST['quantity'.$p.''];
$sql = "UPDATE `inventory_db` SET `item`='$items[$p]',`description`='$desc[$p]',`quantity`='$quantity[$p]',`price`='$price[$p]' WHERE `invid` = '$invid[$p]'";
$p++;
}
Is there a more efficient way of doing this? Or do I need to add in a mysqli_close($con); after?
I would run the sql query in the loop itself. Unless you're using the array somewhere later, you can simplify this. It's not clear where $inventorynumber is being set. Also, remember to set autocommit.
mysqli_autocommit($con, TRUE);
$p=0;
while($inventorynumber > $p) {
$invid = $_POST['invid'.$p.''];
$item = $_POST['item'.$p.''];
$desc = $_POST['desc'.$p.''];
$price = $_POST['price'.$p.''];
$quantity = $_POST['quantity'.$p.''];
$sql = "UPDATE `inventory_db` SET `item`='$items[$p]',`description`='$desc[$p]',`quantity`='$quantity[$p]',`price`='$price[$p]' WHERE `invid` = '$invid[$p]'";
mysqli_query($conn, $sql);
$p++;
}
mysqli_close($conn);

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories