having 2 mysqli errors which causes data to not be inserted - php

//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();
}
}

Related

Insert query not inserting no error message

I can't get an INSERT query to INSERT in db. I am not getting any error message and was following a tutorial any help will be greatly appreciated.
$query = "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbc,$query);
//$stmt = mysqli_query($dbc, $query);
if($stmt == false) {
die("<pre>".mysqli_error($dbc).PHP_EOL.$query."</pre>");
}
mysqli_stmt_bind_param($stmt,"ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
//mysqli_stmt_close($stmt);
// Check the results...
if (mysqli_stmt_affected_rows($stmt) == 1)
{
echo'<p>The room has been added.</p>';
// Clear $_POST:
$_POST = array();
}
mysqli_stmt_close($stmt);
} // End of $errors IF.
// End of the submission IF.
Because it does not echo "The room has been added" I suspect the problem is with the mysqli_stmt_affected_rows($stmt) == 1
try this
if ($stmt = mysqli_prepare($dbc, "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)")) {
mysqli_stmt_bind_param("ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
} printf("Error: %s.\n", mysqli_stmt_error($stmt));

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

Is this method of insert correct when using mysqli

I just want to know that when it comes to inserting data into database using mysqli, if this is the best way to do it below or is there a much better way?
$insert = array();
for ($i = 1, $n = $_SESSION['sessionNum']; $i <= $n; ++$i)
{
$insert[] = "'". mysqli_real_escape_string( $_SESSION['id'] ) . ($n == 1 ? '' : $i) . "','". mysqli_real_escape_string( $_SESSION['timeChosen'] ) ."','". mysqli_real_escape_string( date("Y-m-d", strtotime( $_SESSION['dateChosen'] ) ) ) ."'
,'". mysqli_real_escape_string( $_SESSION['textWeight'] ) ."','". mysqli_real_escape_string( $time ) ."','". mysqli_real_escape_string( $_SESSION['textMarks'] ) ."'
,'". mysqli_real_escape_string( $_SESSION['module'] ) ."','". mysqli_real_escape_string( $teacherid ) ."','". mysqli_real_escape_string( $_SESSION['rooms'] ) ."'";
}
$insertsql = "INSERT INTO Session (SessionId, SessionTime, SessionDate, SessionWeight, SessionDuration, TotalMarks, ModuleId, TeacherId, Room)
VALUES (" . implode('), (', $insert) . ")";
$sqlstmt=$mysqli->prepare($insertsql);
$sqlstmt->execute();
The whole point of using prepared statements is to avoid doing half of the work you are doing. The basic idea is that you just create the basic query, prepare it and tell it the variable names you will use instead of the placeholders and then do all the work on the variables.
Your code should be something as follows:
$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(); /* free resources */
It's best to use PDO, and to use a prepared query to which you bind your values. If you have a lot of values to fill in then you can just use positionally based placeholders instead of namebased ones.
<?php
// connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', "username", "password");
// fill in the array, just one after the other since the placeholders will be numbered from 1 to ->count($insert)
$insert = array();
for ($i = 1, $n = $_SESSION['sessionNum']; $i <= $n; ++$i){
$insert[] = $_SESSION['id'] . ($n == 1 ? '' : $i);
$insert[] = $_SESSION['timeChosen'];
$insert[] = date("Y-m-d", strtotime( $_SESSION['dateChosen']));
$insert[] = $_SESSION['textWeight'];
$insert[] = $time;
$insert[] = $_SESSION['textMarks'];
$insert[] = $_SESSION['module'];
$insert[] = $teacherid;
$insert[] = $_SESSION['rooms'];
}
$query = $pdo->prepare('INSERT INTO Session
(SessionId, SessionTime, SessionDate, SessionWeight,
SessionDuration, TotalMarks, ModuleId, TeacherId, Room)
VALUES' .
//repeat the 9 placeholders for $_SESSION['sessionNum'] and cut of the trailing ,
substr(str_repeat('(?,?,?,?,?,?,?,?,?),',$_SESSION['sessionNum']),0,-1));
// now we bind the placeholder with the corresponding value in the array
for($i = 0;$i < count($insert);$i++){
$query->bindParam(($i + 1),$insert[$i]);
}
// finally we execute the query
$query->execute();
And that's it really. (I wrote this from memory, haven't tested it but for php -l but you get the general idea and I'm pretty sure it'll work. ;) )

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.

mysqli::prepare is not returning an object?

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.

Categories