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. ;) )
Related
Im having some trouble getting my SQL query to 'insert into' my database, is it allowed to use variables as table name, field name, and values?
Here my code:
$nameOfDBFromA = "vagtplanA" . $_GET["from"];
$flytnedToQ1 = $con->prepare("SELECT * FROM $nameOfDBToA WHERE ansatId='$_GET[ansatId]' ORDER BY id DESC");
$flytnedToQ1->execute();
$flytnedTo1 = $flytnedToQ1->fetch();
$nameOfFieldToA1 = "a" . $_GET["to"] . "1";
$nameOfFieldToA2 = "a" . $_GET["to"] . "2";
$nameOfFieldToA3 = "a" . $_GET["to"] . "3";
$nameOfFieldToA4 = "a" . $_GET["to"] . "4";
$nameOfFieldToA5 = "a" . $_GET["to"] . "5";
$nameOfFieldToA6 = "a" . $_GET["to"] . "6";
$nameOfFieldToA7 = "a" . $_GET["to"] . "7";
$redigeringsTidspunkt = date("j M Y");
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES($_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]) ")
or die(mysql_error());
$flytnedTA->execute();
SOLVED! I just put my arrays into it own variable
$intoVarToA1 = $flytnedTo1[$nameOfFieldToA1];
$intoVarToA2 = $flytnedTo1[$nameOfFieldToA2];
$intoVarToA3 = $flytnedTo1[$nameOfFieldToA3];
$intoVarToA4 = $flytnedTo1[$nameOfFieldToA4];
$intoVarToA5 = $flytnedTo1[$nameOfFieldToA5];
$intoVarToA6 = $flytnedTo1[$nameOfFieldToA6];
$intoVarToA7 = $flytnedTo1[$nameOfFieldToA7];
You shouldn't substitute variables into the query, you should use bind_param() to provide parameter values for the prepared query.
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ")
or die(mysqli_error($con));
$flytnedTA->bind_param("sssssssss", $_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]);
$flytnedTA->execute();
You also need to call mysqli_error($con), not mysql_error().
One of your mistakes is when you want to access a value in an array inside of a string, you can't do:
"$flytnedTo1[$nameOfFieldToA1]"
You have to do it like this:
"{$flytnedTo1[$nameOfFieldToA1]}" // use curly brackets
If you have variables like that, you can insert data into db like below in php.
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
Is not a good practice put _GET or _POST variables directly on query, use mysqli_real_escape_string to clear the value in variable.
The array values are not parsed directly in strings, you must enclose the expression in {}:
For this: " $flytnedTo1[$nameOfFieldToA3] " replace with: "'{$flytnedTo1[$nameOfFieldToA3]}'" , the result value also need to enclosed by '' singlequoes for sql string value.
$flytnedTA = $con->prepare("INSERT INTO $nameOfDBFromA (ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2, $nameOfFieldToA3,
$nameOfFieldToA4, $nameOfFieldToA5, $nameOfFieldToA6, $nameOfFieldToA7)
VALUES({$_GET['ansatId']}, '$redigeringsTidspunkt', '{$flytnedTo1[$nameOfFieldToA1]}', '{$flytnedTo1[$nameOfFieldToA2]}',
'{$flytnedTo1[$nameOfFieldToA3]}', '{$flytnedTo1[$nameOfFieldToA4]}', '{$flytnedTo1[$nameOfFieldToA5]}',
'{$flytnedTo1[$nameOfFieldToA6]}', '{$flytnedTo1[$nameOfFieldToA7]}') ") or die(mysql_error());
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
//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 was wondering how can I check a value from an array to see if its in the database if it is don't added to the database again. How would I be able to do this using PHP & MySQL?
PHP code.
for ($x = 0; $x < count($cat_id); $x++){
$cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
}
Revise PHP code.
if(isset($cat_id)){
for($x = 0; $x < count($cat_id); $x++){
$check_query = mysqli_query($mysqli,"SELECT category_id FROM posts_categories WHERE category_id = '" . $cat_id[$x] ."' AND post_id = '" . $post_id . "'");
if ($check_query == TRUE) {
unset($cat_id[$x]);
}
}
for($x = 0; $x < count($cat_id); $x++){
$cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
}
}
You can use INSERT .. ON DUPLICATE UPDATE.
As you're using mysqli you should probabaly use prepared statements (from both a security and performance standpoint)
$stmt = $mysqli->prepare("INSERT IGNORE INTO posts_categories (category_id, post_id, date_created) VALUES (?, ?, ?)");
// Should use a prepared statement here.
foreach ($categories as $key => $cat) {
// Bind params
$stmt->bind_param('iis', $cat, $post_id, 'NOW()');
// Exectute the query
$stmt->execute();
}
// Close the connection!
$mysqli->close();
NOTE: I also used INSERT IGNORE, so the insert will silently fail if the key exists.
$sql = "SELECT * FROM your_table WHERE your_column='".$yourArray['value']."'";
if(!mysql_num_rows(mysql_query($sql))){
// no rows so add it to the database...
}