This question already has answers here:
When to close Prepared Statement
(2 answers)
When to call mysqli::close
(4 answers)
Closed 1 year ago.
Is it necessary to close the prepared statement in php by using $stmt->close();
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
php_mysqli library was written in low level languages which requires manual memory management. Whenever you allocate a new resource it takes some memory from the device RAM to host the allocated data.
Closing allocated resource free's that memory that later could be again used for another allocation requests or lets Operation System to give that part of memory to another programs when needed.
In short: if you want to make your code memory efficient you might want to close resources you've allocated previously. If you don't really care about the efficiency you might not close the resources.
Another think to keep in mind that Operation System also frees allocated memory chunks whenever a program completes execution. So, closing resources manually might not make a noticable improvement in some situations.
References:
C Memory Management - MIT
mysqli_stmt::close - PHP
Related
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
I have 2 files, file number is the connection, it look like this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName= "abc";
// Create connection
$db = new mysqli($servername, $username, $password, $dbName);
?>
then the second file, where I include the first one, look like this
include '../db.php';
$stmt = $db->prepare("INSERT INTO test(a,b,c,d,e) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssis', $a,$b,$c,$d,$e);
$stmt->execute();
$stmt->close();
Why does it execute twice when I run the second file? does it cause by the include of the first file?
You must be running the execute twice for sure. It is not visible from this code why it happened twice, page refresh is good candidate.
Add some debugging output to understand what causes this part of code to be run twice.
In addition to Margus' answer... Is it possible that you are including the second file twice? That would also cause that to happen. You need to be sure that this file is only being run once.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I am trying to test a simple user account registration page for a project for class, and I am trying to create a check that will notify the user if their email is already in the database, and therefore will not add them to it again. Here's my PHP code.
<?php
$collegeid = mysql_real_escape_string('1');
$email = mysql_real_escape_string('abc#test.com');
$password = mysql_real_escape_string(md5('test1'));
$name = mysql_real_escape_string('Test Test');
$bday = mysql_real_escape_string('1900-01-01');
$class = mysql_real_escape_string('Freshman');
//echo "<p>Test</p>";
$servername = "localhost";
$username = redacted;
$serverpassword = redacted;
$dbname = redacted;
$conn = new mysqli($servername, $username, $serverpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$checkquery = "SELECT * FROM Student WHERE Email = '$email'";
$insertquery = "INSERT INTO Student (CollegeID, Name, Birthday, Email, Classification, Password) VALUES ('$collegeid', '$name', '$bday', '$email', '$class', '$password')";
if (mysql_num_rows($conn->query($checkquery)) > 0)
{
echo "Error: Email already in use";
}
else
{
$conn->query($insertquery);
echo "Account Created.";
}
?>
However, it always tells me the account is created, regardless of whether or not that user is in the database.
You are mixing mysql and mysqli functions. You should not use mysql functions as they are deprecated and you seem to be using mysqli for almost everything except escaping your values and checking the number of found rows.
The problem is caused by your use of mysql_real_escape_string. When no mysql_* database connection is found, that returns false which is the equivalent of an empty string so you are checking for empty values in your database and everytime you don't find that, you add a new row.
To secure yourself against sql injection on mysqli, you should switch to prepared statements instead of using mysqli_real_escape_string.
Edit: It is also mysql_num_rows that is returning false in case of an error...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
hello i have this code which try to insert data in the database but i face error rong parameter count for mysqli
<?php
session_start();
$regValue = $_GET['regName'];
echo "Your registration is: ".$regValue.".";
$servername = "localhost";
$username = "root";
$password = "b4sonic";
$dbname = "b4sonic2";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO b4sonic (first_name) VALUES (?)");
$stmt->bind_param( $firstname);
// set parameters and execute
$firstname = "John";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
please i ness rapid respone because i work on project and i should comlete it but this probelm
Fred addressed one issue. At the time of bind_param, $firstname isn't defined.
You also aren't calling bind_param correctly.
The first parameter needs to identify the variable type. For instance 's' for string. Refer to the link I added.
// define the variable first
$firstname = "John";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO b4sonic (first_name) VALUES (?)");
$stmt->bind_param("s", $firstname);
// set parameters and execute
$stmt->execute();
put $firstname above your line:
// prepare and bind
$firstname = "John";
$stmt = $conn->prepare("INSERT INTO b4sonic (first_name) VALUES ('$firstname')");