PHP MySQL INSERT and UPDATE from ODBC - php

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.

Related

Insert Multi Row Oracle result set into MYSQL using 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)");

Can't Insert data in MySql Table, but i can retrieve data just fine

I can conect to my database just fine, but whenever I try to insert data I get a "Call to a member function bind_param() on a non-object" error, which I know means that I must have mistyped the name of a slot, or something, but I just can't see it, I'm connecting locally, do I have to set up something in MyPhP to allow data to be added from a php file? Thanks in advance.
<?php
include 'connect.php';
if (isset($_POST['Slot1'])) {
$Slot1 = $_POST['Slot1'];
}
if (isset($_POST['Slot2'])) {
$Slot2 = $_POST['Slot2'];
}
if (isset($_POST['Slot3'])) {
$Slot3 = $_POST['Slot3'];
}
if (isset($_POST['Slot4'])) {
$Slot4 = $_POST['Slot4'];
}
if (isset($_POST['Slot5'])) {
$Slot5 = $_POST['Slot5'];
}
if (isset($_POST['Slot6'])) {
$Slot6 = $_POST['Slot6'];
}
if (isset($_POST['Slot7'])) {
$Slot7 = $_POST['Slot7'];
}
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?");
$stmt->bind_param('sssssss',$Slot1,$Slot2,$Slot3,$Slot4,$Slot5,$Slot6,$Slot7);
$stmt->execute();
$stmt->close();
header("Location: Display.php")
?>
You have missed one end parenthese
Replace
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?");
To
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,
Slot6, Slot7)
VALUES (?, ?, ?, ?, ?, ?,?)");
Try to change your query to
$stmt = $db->prepare("INSERT INTO `tabel` (Slot1, Slot 2, Slot3, Slot4,Slot5,Slot6, Slot7)VALUES (?, ?, ?, ?, ?, ?,?)");

Stored procedure in while affected only first row

I try to insert some data with php and a stored procedure. The stored procedure works fine but only for the first row.
PHP:
$sql = "SELECT * FROM [importliste_TCSv3]";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false ) {
die (print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt)) {
// print works fine without call proc
$query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
$params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);
$stmt = sqlsrv_query($conn, $query, $params);
if ($stmt === false) {
die (print_r(sqlsrv_errors(), true));
}
}
Stored Procedure:
ALTER proc [dbo].[difInport]
#mandant_id varchar(50),
#kostenstelle varchar(50),
#vorname varchar(50),
#nachname varchar(50),
#ci_nummer int,
#anzahl_monitore_old int,
#raum varchar(50),
#gebäude varchar(50),
#bemerkung text,
#hardware_typ varchar(50),
#anzahl_monitore_new varchar(50),
#zubehör text
as
BEGIN
SET NOCOUNT ON;
DECLARE
#latestPersonID int,
#latestCmoID int,
#latestFmoID int
INSERT INTO [RC.Persons] (kostenstelle, vorname, nachname) VALUES (#kostenstelle, #vorname, #nachname);
SET #latestPersonID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.CMO] (ci_nummer, anzahl_monitore, raum, gebäude, bemerkung) values (#ci_nummer, #anzahl_monitore_old, #raum, #gebäude, #bemerkung);
SET #latestCmoID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.FMO] (hardware_typ, anzahl_monitore, zubehör) values (#hardware_typ, #anzahl_monitore_new, #zubehör);
SET #latestFmoID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.Persons_RC.CMO] (cmo_id, person_id) VALUES (#latestCmoID, #latestPersonID);
INSERT INTO [RC.Persons_RC.FMO] (fmo_id, person_id) VALUES (#latestFmoID, #latestPersonID);
INSERT INTO [RC.Persons_RC.Mandant] (person_id, mandant_id) VALUES (#latestPersonID, #mandant_id);
END
I read this question: Call mysql PROCEDURE inside while loop works only first time
but I dont give any result set or is the set declaration with a select the result problem?
You are overwriting your $stmt variable. Change the name of the variable you use in the while loop:
while ($row = sqlsrv_fetch_array($stmt)) {
// print works fine without call proc
$query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
$params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);
$stmt_proc = sqlsrv_query($conn, $query, $params);
if ($stmt_proc === false) {
die (print_r(sqlsrv_errors(), true));
}
}

is it possible to utilize two $stmt mysqli

Hello I have a question when I use my $stmt to execute an insert query into my database it works perfectly fine, however when I use a $stmt2 after that execute to UPDATE a different table it won't update the table even though to my understanding the code is correct.
The code I have tried to fix many times is as so
$mysqli= my database connection
$stmt = $mysqli->prepare("INSERT INTO `test_table`(datenow,test1,test2,test3,test4,test5,test6,test7,test8,
test9,test10,test11,test12,test14,test15,test16,test17,test18,)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
$stmt->bind_param('ssssssssssssssssss',$test1,$test2,$test3,$test4,$test5,$test6,$test7,$test8,$test9,$test10,$test11,$test12,$test13,$test14, $test15,$test16,$test17,$test18);
$stmt1 = $mysqli->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
$stmt1->execute();
$stmt->execute();
Any help would be very appreciated thanks!
A prepared statement can only execute one MySQL query. You can prepare as many statements as you want in different variables
so you can change it as:
$stmt1 = $link->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
to
$stmt1 = $mysqli->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
see no need of $link, you can prepare many statement for different variable...Thanks

My code is not inserting data into database

I had an old mysql code where it successfully inserted values into the database. But as that people are now stating that mysqli is better to use (can't use PDO because of my version of php is below 5.3), I have tried to change my code so that it uses mysqli instead of mysql.
The problem is that it now does not insert values into the database since making this change. I am a mysqli novice so I would really appreciate it if somebody can help me change the code below so that mysqli can be used to insert data into the database. What am I doing wrong? There are no errors in the error report.
Below is my current attempt on this:
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$sql = "SELECT TeacherId FROM Teacher WHERE (TeacherUsername = ?)";
$stmt=$mysqli->prepare($sql);
$stmt->bind_param("s",$_SESSION['teacherusername']);
$stmt->execute();
$record = $stmt->fetch();
$teacherid = $record['TeacherId'];
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$time = str_replace(array(' Hrs ', ' Mins ', ' Secs'), array(':', ':', ''), $_SESSION['durationChosen']);
$insertsql = "INSERT INTO Session (SessionId, SessionTime, SessionDate, SessionWeight, SessionDuration, TotalMarks, ModuleId, TeacherId, Room) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$insert = $mysqli->prepare($insertsql);
for ($i = 1, $n = $_SESSION['sessionNum']; $i <= $n; ++$i) {
$sessid = $_SESSION['id'] . ($n == 1 ? '' : $i);
$sessdate = date("Y-m-d", strtotime($_SESSION['dateChosen']));
$insert->bind_param("sssssssss", $sessid, $_SESSION['timeChosen'], $sessdate,
$_SESSION['textWeight'], $time, $_SESSION['textMarks'],
$_SESSION['module'], $teacherid, $_SESSION['rooms']);
$insert->execute();
}
}
Looks like you're missing the ending quote on this line:
$insertsql = "INSERT INTO Session (
SessionId, SessionTime, SessionDate, SessionWeight,
SessionDuration, TotalMarks, ModuleId, TeacherId, Room)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
Make it
$insertsql = "INSERT INTO Session (
SessionId, SessionTime, SessionDate, SessionWeight,
SessionDuration, TotalMarks, ModuleId, TeacherId, Room)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
It also looks like you need to put your for loop before you bind the params, since you're using the results of said for loop in the bind.

Categories