My code is not inserting data into database - php

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.

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 (?, ?, ?, ?, ?, ?,?)");

MySQLi Insert Into If

The issue I am having is the PHP code below only inserts the data into one table blue. What I want is if the directory category from the POST is equal to for example blue INSERT into Table blue , but if it is equal to yellow INSERT into yellow, but if it's equal to red INSERT into table red.
The only answers I have found deal with insert if exist but not multiple insert if statements. Any help would be greatly appreciated. I am just learning PHP code.
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $_POST['firstname'], $_POST['lastname'], $_POST['city'], $_POST['state'], $_POST['zipcode'], $_POST['directorycategory'], $_POST['active']);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
#oremIpsum1771 Your answer works the best. The final code is as follows
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
if($directorycategory == 'Employer'){
$query = ("INSERT INTO employer(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
}
else if($directorycategory == 'Blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Green'){$query = ("INSERT INTO green(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Red'){$query = ("INSERT INTO red(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Orange'){$query = ("INSERT INTO orange(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $firstname, $lastname, $city, $state, $zipcode, $directorycategory, $active);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
I'm not seeing where you have the control structure for the query. If i'm understanding the problem correctly, I would think that you would need something like this:
if(directorycategory == 'blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if(directorycategory == 'yellow'){$query = ("INSERT INTO yellow(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
etc....
$query = ("INSERT INTO ".$_POST['directorycategory']."(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
http://php.net/manual/en/language.operators.string.php
You can use the period to concatenate strings with variables to make 1 big string.

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.

values not inserting into db while using mysqli

I am using mysqli to try and retrieve the teacher's username and then insert all of the values into the dataabse. The problem though is that nothing is being inserted into the database.
I am getting no errors in my error report so I think I am just doing something wrong when it comes to inserting values into the database using mysqli but I am not sure what. Can anybody give me any pointers on why it is not inserting values into the db?
Below is the code:
$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);
// You only need to call bind_param once
$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);
$insert->bind_params("sssssssss", $sessid, $_SESSION['timeChosen'], $sessdate,
$_SESSION['textWeight'], $time, $_SESSION['textMarks'],
$_SESSION['module'], $teacherid, $_SESSION['rooms']);
for ($i = 1, $n = $_SESSION['sessionNum']; $i <= $n; ++$i) {
$sessid = $_SESSION['id'] . ($n == 1 ? '' : $i);
$sessdate = date("Y-m-d", strtotime($_SESSION['dateChosen']));
$insert->execute();
}
$insert->close();
}
Try to debug this thing line by line:
set your error reporting to error_reporting(E_ALL); in php file or error_reporting = E_ALL in php ini
does the db connection work ?
echo the sql query before using it
it the query seems to be correct: rebuild it to ONE value and rebuild it step by step to find out where's the error

Categories