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
Related
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 (?, ?, ?, ?, ?, ?, ?, ?, ?)");
When i var_dump($q), I can see the records that is to be inserted into the mysql database, but when I try to do this $result = mysqli_query($con,$q);, the system is not returning an error message neither is the record inserted.
<?php
$con = #mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
foreach( $Grade as $key => $v )
{
$fault_code = $key;
$q = sprintf( 'INSERT INTO `history_tb` VALUES ("%s", "%s", "%s", "%s", "%s")', $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']);
//var_dump($q);
$result = mysqli_query($con,$q);
}
}
?>
INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);
$query = "INSERT INTO table_name( name, address) VALUES ('jony', 'test1'),('bob', 'test2')";
mysql_query($query);
There are two things to tackle before anything else.
Using prepared statements
Since we are using prepared statements, make use of this functionality for inserting multiple values.
Change your code into the following (only amended inside the if statement):
<?php
$con = #mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
$stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"); //Prepare the sql command
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']); // Bind the values in order to the ?'s
$stmt->execute(); // Execute the completed sql command
}
$stmt->close(); // Close the database connection
}
?>
What we are doing here is saying my SQL is
INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)`
now loop through your array and call this SQL with the parameters given at each section of the loop.
This solves the first two issues of not using prepared statements and looping when using prepared statements.
Try this and lets see if records get inserted
I'd also check that the foreach is correct, maybe it needs to be
foreach ($Grade as $v)
but without seeing the data I can't confirm.
You can also take this further to add error handling:
if ($stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"))
{
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
// Bind the values in order to the ?'s or log error
if(!$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']))
{
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
// Execute the completed sql command or log error
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
$stmt->close(); // Close the database connection
}
else
{
die('prepare() failed: ' . htmlspecialchars($con->error));
}
Edit: added error handling
//connected to db
if (isset($_POST['teacherusername'])) {
$_SESSION['teacherusername'] = $_POST['teacherusername'];
}
$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'];
$stmt->close();
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();
if ($insert->errno) { echo "Error in insert: $insert->error<br>\r\n"; }
$insert->close();
}
}
UPDATE:
The previous errors have been fixed, but I am now getting 4 warnings which are displayed below:
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Couldn't fetch mysqli_stmt in /web/stud/.../Mobile_app/insertsession.php on line 177
Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: Couldn't fetch mysqli_stmt in /web/stud/.../Mobile_app/insertsession.php on line 179
Warning: main() [function.main]: Couldn't fetch mysqli_stmt in /web/stud/.../Mobile_app/insertsession.php on line 181
Warning: mysqli_stmt::close() [mysqli-stmt.close]: Couldn't fetch mysqli_stmt in /web/stud/.../Mobile_app/insertsession.php on line 185
As that mysqli is now inserting data into the database, do I deal with these warnings or shall I leave them alone?
PROBLEM IS SOLVED, FOR FUTURE VIEWERS PLEASE LOOK AT DAVE RANDOM'S ANSWER
Simply add this line at the end of your loop and it should work:
$insert->close();
This will work if you don't still have an unclosed statement from code that is executed before the code you show. You must close the previous statement before another can be executed.
See mysqli_stmt::close() for more information.
EDIT
Try this code:
//connected to db
$sql = "
SELECT TeacherId
FROM Teacher
WHERE TeacherUsername = ?
";
if (!$stmt = $mysqli->prepare($sql)) {
// Handle errors with prepare operation here
}
// Bind parameter for statement
$stmt->bind_param("s", $_SESSION['teacherusername']);
// Execute the statement
$stmt->execute();
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$stmt->bind_result($teacherid);
// This populates $teacherid
$stmt->fetch();
// Close the statment
$stmt->close();
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
(?, ?, ?, ?, ?, ?, ?, ?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
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();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
}
}
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.
I got some problem with binding some parameters in MYSQL statement in php. It is throwing an error when count($posts) > 1 on the marked line below. Anyone who know what I've done wrong?
The error is: Call to a member function bind_param() on a non-object. It is also reporting comman out of sync?(on the marked line below)
<?php
include '../../main/mainFunctions2.php';
$futurePosts = json_decode($_POST['futurePosts']);
$repeatSerie = null;
if(count($posts) > 1){
//Get new repeatSeries
$stmt = $mysqli->prepare("
SELECT repeatSerie
FROM timeSpaces_futurePosts
ORDER BY repeatSerie DESC
LIMIT 1
");
$stmt->execute();
$stmt->bind_result($repeatSerie);
$stmt->fetch();
$repeatSerie = ((int)$repeatSerie + 1);
}
$timeStamp = time();
foreach($posts as $fp){
$title = $fp->title;
$startDate = $fp->startDate;
$endDate = $fp->endDate;
$startTime = $fp->startTime;
$endTime = $fp->endTime;
$location = $fp->location;
$latLong = $fp->latLong;
$info = $fp->info;
$photoId = $fp->photoId;
$invited = $fp->invited;
if($invited != null){
$invited = 1;
}else{
$invited = 0;
}
$reminderType = $fp->reminderType;
$reminderTimeStamp = $fp->reminderTimeStamp;
$repeatSerie = $repeatSerie;
$stmt = $mysqli->prepare("
INSERT INTO futurePosts (profileId, title, startDate, endDate, startTime, endTime, location, latLong, info, photoId, invited, reminderType, reminderTimeStamp, repeatSerie)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('isssiisssiisii', $profileId, $title, $startDate, $endDate, $startTime, $endTime, $location, $latLong, $info, $photoId, $invited, $reminderType, $reminderTimeStamp, $repeatSerie);
//The line above: Call to a member function bind_param() on a non-object
$stmt->execute();
$futurePostId = $mysqli->insert_id;
if($invited == 1){
foreach($fp->invited as $friendsId){
$friendsId = $friendsId;
$stmt = $mysqli->prepare('
INSERT INTO futurePosts_invited (profileId, futurePostId, timeStamp)
VALUES (?, ?, ?)
');
$stmt->bind_param('iii', $friendsId, $futurePostId, $timeStamp);
$stmt->execute();
}
}
}
echo 'TRUE';
?>
This is most likely because $stmt = $mysqli->prepare(...); line fails due to SQL syntax error. Try echoing $mysqli->error to see what's wrong with it.
Try calling $stmt->store_result(); after execution of your SELECT statement and before issuing any other queries to MySQL.
Side note: you should prepare your statement before foreach loop. That will get you a bit of performance gain, since the statement will only be compiled once and only parameters will be sent to server on each loop run.
mysqli_prepare() returns a statement object or FALSE if an error
occurred.