Insert Multi Row Oracle result set into MYSQL using PHP - php

A little background. I have an Oracle database that I am trying to query and then insert into a local MYSQL database so that I can generate canned reports. I have been trying to figure out this insert into Mysql for a while now. I have the Oracle portion running correctly but when I try to insert I have been getting a syntax error in mysql.
The result set comes back with 8 rows the first of which is the Key in MYSQL. I would really like to convert this insert query I built into a insert on duplicate key update statement but am lost on how I would do this properly. Any help you guys can provide would be appreciated.
$db1 = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=HOST)(PORT = 1521))(CONNECT_DATA=(SERVICE_NAME=Service)))';
$c1 = oci_connect("Userid", "Pass", $db1);
$sql = oci_parse($c1, "select statement") ;
oci_execute($sql);
$i = 0;
while ($row = oci_fetch_array($sql)){
$i++;
$k = $row[0];
$dte = $row[1];
$cus = $row[2];
$odr = $row[3];
$lin = $row[4];
$cas = $row[5];
$lpo = $row[6];
$cpl = $row[7];
$cpo = $row[8];
};
$db_user = "userid";
$db_pass = "Pass";
$db = new PDO('mysql:host=host; dbname=databasename', $db_user, $db_pass);
$stmt = $db->prepare("INSERT INTO `cuspi` (k, dte, cus, odr, lin, casa, lpo, cpl, cpo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$recordcount = count($k);
for ($i = 0; $i < $recordcount; $i++) {
$records[] = [
$k[$i],
$dte[$i],
$cus[$i],
$odr[$i],
$lin[$i],
$casa[$i],
$lpo[$i],
$cpl[$i],
$cpo[$i],
];
}
foreach ($records as $record) {
$stmt->execute($record);
}
?>

I was able to figure out the Answer. I was missing the grave accent around the column references for the insert.
Original
$stmt = $db->prepare("INSERT INTO `cuspi` (k, dte, cus, odr, lin, casa, lpo, cpl, cpo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
Fixed
$stmt = $db->prepare("INSERT INTO `cuspi` (`k`, `dte`, `cus`, `odr`, `lin`, `casa`, `lpo`, `cpl`, `cpo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

Related

MySQL syntax error when using question mark placeholders in prepared statement

Tried everything I can think of and I've narrowed down to the "?" placeholders.
I've tried replacing the "?" placeholders with random text and all works well (except of course it keeps overwriting the same row).
The error I get:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
produ' at line 2
Here is my code (I would provide more but it all works well except for this bug, and if I remove the "?" placeholders then all works perfectly except that the values are not dynamic, but please ask if you suspect the issue is elsewhere):
// Create MySQL connection to ds_signifyd_api
$mysqli = mysqli_connect( $db_server_name, $db_username, $db_password, $db_name );
// Check connection
if ($mysqli->connect_error) {
exit( $mysqliFailedBody );
}
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = "";
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
//... more variables here...
$tags = mysqli_real_escape_string($mysqli, $tags);
if (!mysqli_query($mysqli, $mainProdQueryStmt)) {
printf("Errormessage: %s\n", mysqli_error($mysqli));
}
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
$mainProdQuery->execute();
// $mainProdQuery->close();
}
UPDATE
Implemented the fixes mentioned here:
1. Stopped using mysqli_real_escape_string
2. Binding variables outside loop
3. Using only the object oriented method, as opposed to mixing them as in the case of mysqli_query($mysqli, $mainProdQueryStmt) VS $mysqli->prepare($mainProdQueryStmt) as it should have been -- this solved the "?" placeholders syntax error being incorrectly reported
Now everything works perfectly, no errors.
Updated Code:
$mainProdQueryStmt = "INSERT INTO dss_products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$mainProdQuery = $mysqli->prepare($mainProdQueryStmt);
if ($mainProdQuery === FALSE) {
die($mysqli->error);
}
$product_id = $product_title = $body_html = $vendor = $product_type = $created_at = $handle = $updated_at = $published_at = $template_suffix = $published_scope = $tags = "";
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
if ($mainProdQuery) {
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
$product_title = $product['title'];
$body_html = $product['body_html'];
$vendor = $product['vendor'];
$product_type = $product['product_type'];
$created_at = $product['created_at'];
$handle = $product['handle'];
$updated_at = $product['updated_at'];
$published_at = $product['published_at'];
$template_suffix = $product['template_suffix'];
$published_scope = $product['published_scope'];
$tags = $product['tags'];
if (!$mysqli->prepare($mainProdQueryStmt)) {
printf("Errormessage: %s\n", $mysqli->error);
}
$mainProdQuery->execute();
}
}
When you use placeholders you have to use mysqli_prepare(), you can't use mysqli_query(). It looks like you intended to do that, but somehow that code got lost, since you use a variable $mainProdQuery that you never assigned.
You should prepare the query and bind the parameters just once, outside the loop. Then call execute() inside the loop.
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
title = VALUES(title),
body_html = VALUES(body_html),
vendor = VALUES(vendor),
product_type = VALUES(product_type),
created_at = VALUES(created_at),
handle = VALUES(handle),
updated_at = VALUES(updated_at),
published_at = VALUES(published_at),
template_suffix = VALUES(template_suffix),
published_scope = VALUES(published_scope),
tags = VALUES(tags)";
$mainProdQuery = $mysqli->prepare($mainProdQueryStmt);
$mainProdQuery->bind_param("isssssssssss", $product_id, $product_title, $body_html, $vendor, $product_type, $created_at,
$handle, $updated_at, $published_at, $template_suffix, $published_scope, $tags);
foreach ($dss_product_db_array as $product) {
$product_id = $product['id'];
//... more variables here...
$mainProdQuery->execute();
}
You're running the query before it's properly prepared, and then, after the fact, attempting to bind to something that's not the right type, it's not a statement handle but a result set. You need to structure it this way:
$mainProdQueryStmt = "INSERT INTO products (`product_id`, `title`, `body_html`, `vendor`, `product_type`, `created_at`, `handle`, `updated_at`, `published_at`, `template_suffix`, `published_scope`, `tags`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
product_id = VALUES(product_id),
...
tags = VALUES(tags)";
// Prepare the statement to get a statement handle
$stmt = $mysqli->prepare($mainProdQueryStmt);
foreach ($dss_product_db_array as $product) {
// Bind to this statement handle the raw values (non-escaped)
$stmt->bind_param("isssssssssss",
$product['id'], $product['title'], ...);
// Execute the query
$stmt->execute();
}
Try to avoid creating heaps of throw-away variables an just bind directly to the values in question, like those in $product. The variables do nothing useful and only introduce opportunities for silly mistakes.
Try using PDO(PhP Data Objects) prepared statements. It's less painful to work with and cross database i.e can be used with any RDBMS. See PDO Official Documentation or here

Create child tables from table with INSERT INTO and no duplicate

To be clear, this what I need :
So,
I get my data for table "recap" from a JSON file.
What I need is two tables :
First : table "Voyage" with no duplicate (I try a lot but all failed)
Second : table "simplifiee" wich is the same as "recap" but with a ID voyage column from table "voyage" (I'm pretty sure I need a JOIN, left, full, other.. but not enough good at doing this..)
Let me know if you don't understand.
This is my code :
<?php
require 'database.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// JSON content //
$json = file_get_contents("https://xxx");
// Décode //
$parsed_json = json_decode($json);
foreach ($parsed_json->{'results'} as $result)
{
// Parsed JSON //
$date = $result->{'xxx'};
$transporteur = $result->{'xxx'};
$depart = $result->{'xxx'};
$arrivee = $result->{'xxx'};
$prixhaut = $result->{'xxx'};
$prixbas = $result->{'xxx'};
// Table "recap" Creation //
$sql = "INSERT INTO recap (date,transporteur,depart,arrivee,prixhaut,prixbas) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($date,$transporteur,$depart,$arrivee,$prixhaut,$prixbas));
}
Database::disconnect();
?>

What to put in a MySQL auto-increment primary key field when inserting a row?

I'm new to PHP and I'm having a little trouble setting up my code to auto increment IDs for SQL. I'm aware that the method that I am attempting isn't a very good approach and know about the risks of race conditions etc. This will be temporary until I sort the rest of my code out properly.
Could somebody please tell me what I am doing wrong here? Or help me to get valid code?
My Class:
<?php
$user = 'root';
$pass = '';
$db = 'testuser';
$con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');
$data = json_decode(trim(key($_POST), '[]'), true);
$email = $data['email'];
$name = $data['name'];
$shortDes = $data['shortDes'];
$longDes = $data['longDes'];
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
Focusing on the following snippet:
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
Just needed to remove the value for the auto incremented field altogether.

Checking if email is already taken [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
In my PHP file I want to check if the email is already taken before inserting the data into my mysql database.
I cant find anything wrong with my code but it wont work.
PHP code:
<?php
$conn = mysqli_connect("s.amazonaws.com", "username", "pass", "SellerAccounts");
//If statement echos back to the browser if we connected to the server or not.
//Store the data from the POST (text from the user) into a variable.
$Sellers_CompanyName = $_POST["SellersCompanyName"];
$Sellers_CompanyWebsite = $_POST["SellersCompanyWebsite"];
$Sellers_IndustryName = $_POST["SellersIndustryName"];
$Sellers_SecondaryIndustryName = $_POST["SellersSecondaryIndustryName"];
$Sellers_FirstContactFirstName = $_POST["SellersFirstContactFirstName"];
$Sellers_FirstContactLastName = $_POST["SellersFirstContactLastName"];
$Sellers_FirstContactNumber = $_POST["SellersFirstContactNumber"];
$Sellers_FirstContactEmail = $_POST["SellersFirstContactEmail"];
$Sellers_SecondContactFirstName = $_POST["SellersSecondContactFirstName"];
$Sellers_SecondContactLastName = $_POST["SellersSecondContactLastName"];
$Sellers_SecondContactNumber = $_POST["SellersSecondContactNumber"];
$Sellers_SecondContactEmail = $_POST["SellersSecondContactEmail"];
$Sellers_Password = $_POST["Password"];
$result = mysql_query("SELECT * FROM user_info WHERE Sellers_FirstContactEmail = '".$Sellers_FirstContactEmail."'");
if ( mysql_num_rows($result) > 0 ){
echo("Email is already in use");
}else{
//
$statement = mysqli_prepare($conn, "INSERT INTO user_info (Sellers_CompanyName, Sellers_CompanyWebsite, Sellers_IndustryName, Sellers_SecondaryIndustryName, Sellers_FirstContactFirstName, Sellers_FirstContactLastName, Sellers_FirstContactNumber, Sellers_FirstContactEmail, Sellers_SecondContactFirstName, Sellers_SecondContactLastName, Sellers_SecondContactNumber, Sellers_SecondContactEmail, Sellers_Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
mysqli_stmt_bind_param($statement, "sssssssssssss", $Sellers_CompanyName, $Sellers_CompanyWebsite, $Sellers_IndustryName, $Sellers_SecondaryIndustryName, $Sellers_FirstContactFirstName, $Sellers_FirstContactLastName, $Sellers_FirstContactNumber, $Sellers_FirstContactEmail, $Sellers_SecondContactFirstName, $Sellers_SecondContactLastName, $Sellers_SecondContactNumber, $Sellers_SecondContactEmail, $Sellers_Password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
if(mysqli_query($connection, $sql_query)){
// echo" Data insertion success...";
}
}
mysqli_close($conn);
?>
i can insert everything fine and connect to the DB
You cannot mix MySQL functions with MySQLi functions. And also your connection is $conn, so using $connection will not work.
<?php
$conn = mysqli_connect("s.amazonaws.com", "username", "pass", "SellerAccounts");
$Sellers_CompanyName = $_POST["SellersCompanyName"];
$Sellers_CompanyWebsite = $_POST["SellersCompanyWebsite"];
$Sellers_IndustryName = $_POST["SellersIndustryName"];
$Sellers_SecondaryIndustryName = $_POST["SellersSecondaryIndustryName"];
$Sellers_FirstContactFirstName = $_POST["SellersFirstContactFirstName"];
$Sellers_FirstContactLastName = $_POST["SellersFirstContactLastName"];
$Sellers_FirstContactNumber = $_POST["SellersFirstContactNumber"];
$Sellers_FirstContactEmail = $_POST["SellersFirstContactEmail"];
$Sellers_SecondContactFirstName = $_POST["SellersSecondContactFirstName"];
$Sellers_SecondContactLastName = $_POST["SellersSecondContactLastName"];
$Sellers_SecondContactNumber = $_POST["SellersSecondContactNumber"];
$Sellers_SecondContactEmail = $_POST["SellersSecondContactEmail"];
$Sellers_Password = $_POST["Password"];
$result = mysqli_query($conn, "SELECT * FROM user_info WHERE Sellers_FirstContactEmail = '$Sellers_FirstContactEmail'");
if ( mysqli_num_rows($result) > 0 ){
echo("Email is already in use");
} else {
$statement = mysqli_prepare($conn, "INSERT INTO user_info (Sellers_CompanyName, Sellers_CompanyWebsite, Sellers_IndustryName, Sellers_SecondaryIndustryName, Sellers_FirstContactFirstName, Sellers_FirstContactLastName, Sellers_FirstContactNumber, Sellers_FirstContactEmail, Sellers_SecondContactFirstName, Sellers_SecondContactLastName, Sellers_SecondContactNumber, Sellers_SecondContactEmail, Sellers_Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
mysqli_stmt_bind_param($statement, "sssssssssssss", $Sellers_CompanyName, $Sellers_CompanyWebsite, $Sellers_IndustryName, $Sellers_SecondaryIndustryName, $Sellers_FirstContactFirstName, $Sellers_FirstContactLastName, $Sellers_FirstContactNumber, $Sellers_FirstContactEmail, $Sellers_SecondContactFirstName, $Sellers_SecondContactLastName, $Sellers_SecondContactNumber, $Sellers_SecondContactEmail, $Sellers_Password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
if(mysqli_query($conn, $sql_query)){
// echo" Data insertion success...";
}
}
mysqli_close($conn);
?>
how about you replace your query with the following?:
$result = mysql_query("SELECT * FROM user_info WHERE Sellers_FirstContactEmail = '".$Sellers_FirstContactEmail."'");
Note the use of string concatenation in the above. In your case, your query is trying to find out emails that match the string "$Sellers_FirstContactEmail", which is not intended - you want to check for the value of that variable.

PHP MySQL INSERT and UPDATE from ODBC

I have a MySQL database that makes a connection to a local MS Access database through ODBC.
I currently have the script properly inserting data from the MS Access database to my MySQL database. The problem is that the MS Access database gets updated daily - so I need code to also update my MySQL database.
Here's what I have - and the result is that i get no errors and nothing is updated (however the insert works fine):
<?php
$conn=odbc_connect('Prod_Schedule','','');
if (!$conn) {
exit("Connection Failed:" . $conn);
}
$sql="SELECT `ID`, `WO_NUM`, `WO_LINE`, `SALES_CCN`, `SO`, `SO_LINE`, `SO_DELIVERY`, `MAS_LOC`, `DUE_DATE`, `FGC`, `HPL`, `DESCRIPTION` FROM `Schedule` WHERE `ID` > $refid AND `HPL` <> 'PART' AND LEN(HPL) > 0";
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
$todays_date = date('m/d/Y', time());
while(odbc_fetch_row($rs)){
$sql = "INSERT INTO `production_schedule` (`ID`, `WO_NUM`, `WO_LINE`, `SALES_CCN`, `SO`, `SO_LINE`, `SO_DELIVERY`, `MAS_LOC`, `DUE_DATE`, `FGC`, `HPL`, `DESCRIPTION`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $db->prepare($sql);
for($i=1;$i<=odbc_num_fields($rs);$i++){
$stmt ->bindValue($i, odbc_result($rs,$i));
}
$stmt ->execute();
$sqlup = "UPDATE `production_schedule`
SET
`ID` = ?,
`WO_NUM` = ?,
`WO_LINE` = ?,
`SALES_CCN` = ?,
`SO` = ?,
`SO_LINE` = ?,
`SO_DELIVERY` = ?,
`MAS_LOC` = ?,
`DUE_DATE` = ?,
`FGC` = ?,
`HPL` = ?,
`DESCRIPTION` = ?
WHERE `DUE_DATE` < '$todays_date'";
for($i=1;$i<=odbc_num_fields($rs);$i++){
$stmt ->bindValue($i, odbc_result($rs,$i));
}
$stmt ->execute();
}
odbc_close($conn);
?>
You should use PHP cron jobs so you can run daily scripts.
Here is an example.

Categories