Jump to content
phpsane

Shall I use mysqli_stmt_free_result($stmt) Or Not ?

Recommended Posts

Php Whizzs!

Here is my login.php partial relevant to the case code:

	$query_1 = "SELECT id,recruits_number,sponsor_username,account_activation_status,id_video_verification_status,id_verification_video_file_url,username,password,primary_domain,primary_website_email,registering_country,registering_ip,registering_browser,registering_os,registering_isp,age_range FROM users WHERE $querying_column = ?"; 
    $stmt_1 = mysqli_prepare($conn,$query_1); 
    mysqli_stmt_bind_param($stmt_1,'s',$login_username_or_email_or_domain); 
    mysqli_stmt_execute($stmt_1); 
    //Check if User's details was successfully extracted or not from 'users' tbl. 
    if (!$stmt_1) 
    { 
        echo "ERROR 1: Sorry! Our system is currently experiencing a problem logging you in!"; 
        exit(); 
    } 
    else 
    { 
        $result_1 = mysqli_stmt_bind_result($stmt_1,$db_id,$db_recruits_number,$db_sponsor_username,$db_account_activation_status,$db_id_video_verification_status,$db_id_verification_video_file_url,$db_username,$db_password,$db_primary_domain,$db_website_email,$db_registering_country,$registering_ip,$registering_browser,$registering_os,$registering_isp,$db_age_range); 
        mysqli_stmt_fetch($stmt_1); 
        mysqli_stmt_close($stmt_1); 
        //Free Result_1 Set 
        mysqli_stmt_free_result($stmt_1); 
	

 

I can login to user account with accurate password. Good!

With wrong password, supposed to get error:

"Incorrect log-in details".

Instead get this:

"Warning: mysqli_stmt_free_result(): Couldn't fetch mysqli_stmt in C:\xampp\htdocs\test\login_v1.php on line 58
Incorrect log-in details".

Line 58 is the last one:

	$result_1 = mysqli_stmt_bind_result($stmt_1,$db_id,$db_recruits_number,$db_sponsor_username,$db_account_activation_status,$db_id_video_verification_status,$db_id_verification_video_file_url,$db_username,$db_password,$db_primary_domain,$db_website_email,$db_registering_country,$registering_ip,$registering_browser,$registering_os,$registering_isp,$db_age_range); 
        mysqli_stmt_fetch($stmt_1); 
        mysqli_stmt_close($stmt_1); 
        //Free Result_1 Set 
        mysqli_stmt_free_result($stmt_1); 
	

 

I read that you use "mysqli_stmt_free_result($stmt)" if you use mysqli_stmt_store_result($stmt). Is this causing the error ? Should I remove mysqli_stmt_free_result($stmt) ?

Or, instead of this:

	        mysqli_stmt_close($stmt_1); 
        //Free Result_1 Set 
        mysqli_stmt_free_result($stmt_1); 
	

 

Should I do this:

	        //Free Result_1 Set 
        mysqli_stmt_free_result($stmt_1); 
	        mysqli_stmt_close($stmt_1);         
	

 

Or, maybe I should add another line ? If so, then what and where ?

Already checked the manual and stuck!

How-about a sample code from your end ?

Edited by phpsane

Share this post


Link to post
Share on other sites
2 hours ago, phpsane said:

I read that you use "mysqli_stmt_free_result($stmt)" if you use mysqli_stmt_store_result($stmt). Is this causing the error ? Should I remove mysqli_stmt_free_result($stmt) ?

You aren't using mysqli_stmt_store_result so you don't need mysqli_stmt_free_result.

Most of the time PHP scripts run quickly, and since PHP will clean up resources for you automatically at the end you often don't need to worry about cleaning them up yourself.

  • Like 1

Share this post


Link to post
Share on other sites

you are likely getting that same error when the the login works, but it is probably being hidden by a redirect.

since you only use mysqli_stmt_free_result() if you are using mysqli_stmt_store_result(), which you aren't in the posted code, doesn't that mean that you shouldn't be using mysqli_stmt_free_result() at all?

you need to switch to the much simpler PDO extension and use exceptions to handled db statement errors. it only takes 4 lines of code to replace the 11 lines you have from the sql query statement through to the fetch statement.

$query = "SELECT id,recruits_number,sponsor_username,account_activation_status,id_video_verification_status,id_verification_video_file_url,username,password,primary_domain,primary_website_email,registering_country,registering_ip,registering_browser,registering_os,registering_isp,age_range FROM users WHERE $querying_column = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$login_username_or_email_or_domain]);
if(!$row = $stmt->fetch())
{
	// the email/username was not found
	// set up the failed login message

}
else
{
	// the email/username was found, check the activation status and then verify the password hash to finish logging in
	// the fetched data is in the associative array $row

}

 

  • Like 1

Share this post


Link to post
Share on other sites
11 minutes ago, mac_gyver said:

you are likely getting that same error when the the login works, but it is probably being hidden by a redirect.

since you only use mysqli_stmt_free_result() if you are using mysqli_stmt_store_result(), which you aren't in the posted code, doesn't that mean that you shouldn't be using mysqli_stmt_free_result() at all?

you need to switch to the much simpler PDO extension and use exceptions to handled db statement errors. it only takes 4 lines of code to replace the 11 lines you have from the sql query statement through to the fetch statement.


$query = "SELECT id,recruits_number,sponsor_username,account_activation_status,id_video_verification_status,id_verification_video_file_url,username,password,primary_domain,primary_website_email,registering_country,registering_ip,registering_browser,registering_os,registering_isp,age_range FROM users WHERE $querying_column = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$login_username_or_email_or_domain]);
if(!$row = $stmt->fetch())
{
	// the email/username was not found
	// set up the failed login message

}
else
{
	// the email/username was found, check the activation status and then verify the password hash to finish logging in
	// the fetched data is in the associative array $row

}

 

I will jump learning pdo after this project (membership script) script is finished after 21 months.

I was told this half hr ago:

"You didn't try hard:

http://php.net/manual/en/mysqli-stmt.close.php wrote:

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.".

And so, following fixed it by re-ordering the lines:

	//Free Result_1 Set 
	mysqli_stmt_free_result($stmt_1); 
	mysqli_stmt_close($stmt_1); 
	

 

Share this post


Link to post
Share on other sites

Mac & Req,

Here is the full script. Not finished yet. Especially, html form part.

ISSUE: 1.
I am having one problem.
When user inputs wrong user details and clicks "Log-in" button, then he gets shown a complete blank page with error message:
"Incorrect log-in details". 
Login form disappears from the page.
This is due to the "exit()" on this lines 59-63:

if (!password_verify($login_password,$db_password)) 
    { 
        echo "Incorrect log-in details<br>"; 
        exit(); 
    } 

Now, if I remove the "exit()", then user gets the same error if his login details are incorrect but the login form still remains on the page. This is what I want so user not have to click BACK button on his browser. But, keeping the "exit()" still runs the script. Waste of bandwidth and/or cpu usage.

Shall I replace it with die() to achieve what I want or do something else ?

Q1a.
How to solve this so script halts but user still sees the login form. And, I want his input to still remain in the form fields and so why don't they especially when I have echoed the form inputs variables like so:

<h2><p align="center"><?php echo "$site_name Member Login Form";?></p></h2> 
<form name = "login_form" method = "post" action="" enctype = "multipart/form-data"> 
    <fieldset> 
        <label for="login_name">Username/Email:</label> 
        <input type="text" name="login_username_or_email_or_domain" id="login_name" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['login_username_or_email_or_domain'])) { echo htmlentities($_POST['login_username_or_email_or_domain']); }?>"><br> 
        <label for="login_pass">Password:</label> 
        <input type="password" name="login_password" id="login_pass" required [A-Za-z0-9] autocorrect=off value=""> 
    </fieldset> 
    <div class="SubmitsAndHiddens"> 
        <label for="login_remember">Remember Log-in Details:</label> 
        <input type="checkbox" name="login_remember" id="login_remember" /> 
        <br> 
        <p align="left"><input type="submit" class="btn btn-default" name="submit" value="Log-in!"></p> 
        <br> 
        <a href="login_password_reset.php">Forgot your password ? Reset it here!</a> 
        <br> 
        <a href="register.php">Don't yet have an account ? Register here!</a> 
    </div> 
</form> 

Note the "value=" in the input field:

<input type="text" name="login_username_or_email_or_domain" id="login_name" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['login_username_or_email_or_domain'])) { echo htmlentities($_POST['login_username_or_email_or_domain']); }?>"><br>         

Q1b.
Should I do the same echoing of the variable in the "Password" input field or not  ? Like so:

<input type="password" name="login_password" id="login_pass" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['login_password])) { echo htmlentities($_POST['login_password']); }?>">    

ISSUE: 2.
Look at this form I found here:
https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
Why is it echoing in "action=" like this:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

Q2a.
Why not like so:

<form action="" method="post">

	<!DOCTYPE html>

	<html lang="en">

	<head>

	    <meta charset="UTF-8">

	    <title>Sign Up</title>

	    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

	    <style type="text/css">

	        body{ font: 14px sans-serif; }

	        .wrapper{ width: 350px; padding: 20px; }

	    </style>

	</head>

	<body>

	    <div class="wrapper">

	        <h2>Sign Up</h2>

	        <p>Please fill this form to create an account.</p>

	        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

	            <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">

	                <label>Username</label>

	                <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">

	                <span class="help-block"><?php echo $username_err; ?></span>

	            </div>    

	            <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">

	                <label>Password</label>

	                <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">

	                <span class="help-block"><?php echo $password_err; ?></span>

	            </div>

	            <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">

	                <label>Confirm Password</label>

	                <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">

	                <span class="help-block"><?php echo $confirm_password_err; ?></span>

	            </div>

	            <div class="form-group">

	                <input type="submit" class="btn btn-primary" value="Submit">

	                <input type="reset" class="btn btn-default" value="Reset">

	            </div>

	            <p>Already have an account? <a href="login.php">Login here</a>.</p>

	        </form>

	    </div>    

	</body>

	</html>
Edited by phpsane

Share this post


Link to post
Share on other sites
24 minutes ago, phpsane said:

How to solve this so script halts but user still sees the login form.

Don't. It is not a "waste" to let your script continue executing. Trying to kill it early is the wrong answer.

The only normal reason anyone should ever exit/die in a script is because they're redirecting with header().

26 minutes ago, phpsane said:

Should I do the same echoing of the variable in the "Password" input field or not  ?

No.

26 minutes ago, phpsane said:

Why not like so:

They both get the same result so it doesn't matter. Perhaps the author didn't know you can have the action empty.

  • Like 1

Share this post


Link to post
Share on other sites
26 minutes ago, requinix said:

Don't. It is not a "waste" to let your script continue executing. Trying to kill it early is the wrong answer.

The only normal reason anyone should ever exit/die in a script is because they're redirecting with header().

No.

They both get the same result so it doesn't matter. Perhaps the author didn't know you can have the action empty.

Hang-on sec.

Qa.

So, both these samples are equal ?

1.

	<form name = "login_form" method = "post" action="" enctype = "multipart/form-data"> 
    <fieldset> 
        <label for="login_name">Username/Email:</label> 
        <input type="text" name="login_username_or_email_or_domain" id="login_name" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['login_username_or_email_or_domain'])) { echo htmlentities($_POST['login_username_or_email_or_domain']); }?>"><br> 
        <label for="login_pass">Password:</label> 
        <input type="password" name="login_password" id="login_pass" required [A-Za-z0-9] autocorrect=off value=""> 
    </fieldset> 
	

 

2.

	<form name = "login_form" method = "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"
	" enctype = "multipart/form-data"> 
    <fieldset> 
        <label for="login_name">Username/Email:</label> 
        <input type="text" name="login_username_or_email_or_domain" id="login_name" required [A-Za-z0-9] autocorrect=off value=""><br> 
        <label for="login_pass">Password:</label> 
        <input type="password" name="login_password" id="login_pass" required [A-Za-z0-9] autocorrect=off value=""> 
    </fieldset> 
	

Qb.

Note the "value=" on both sample forms' input fields.

Which one you recommend out of the 2 samples and why that one ?

Edited by phpsane

Share this post


Link to post
Share on other sites
1 minute ago, phpsane said:

So, both these samples are equal ?

They will both submit to the same location: the current URL.

2 minutes ago, phpsane said:

Which one you recommend out of the 2 samples and why that one ?

The only meaningful difference between them is that the first fills in a provided username while the second does not.

I would recommend the one that behaves the way you want it to behave.

  • Like 1

Share this post


Link to post
Share on other sites

Req,

I edited my previous post. Maybe, your answer will change now ?

Share this post


Link to post
Share on other sites

You made the two samples even more similar to each other. If my answer before was "they're basically the same" then that will be even more true now.

  • Haha 1

Share this post


Link to post
Share on other sites
4 minutes ago, requinix said:

You made the two samples even more similar to each other. If my answer before was "they're basically the same" then that will be even more true now.

Oops!

Fixed it again. But, I guess you will reply same. Lol!

Share this post


Link to post
Share on other sites

Now you've reverted your change and gone back to the original version, so yes my answer is the same.

  • Thanks 1

Share this post


Link to post
Share on other sites
2 hours ago, phpsane said:

And so, following fixed it by re-ordering the lines:

 


	//Free Result_1 Set 
	mysqli_stmt_free_result($stmt_1); 
	mysqli_stmt_close($stmt_1); 
	

@phpsane It really is a waste of our time replying to your posts, isn't it?

Prior to your posting that solution, two people had told you that you don't need mysqli_stmt_free_result(), and why you don't need it.

Yet, still, there it is.

Share this post


Link to post
Share on other sites
1 hour ago, Barand said:

@phpsane It really is a waste of our time replying to your posts, isn't it?

Prior to your posting that solution, two people had told you that you don't need mysqli_stmt_free_result(), and why you don't need it.

Yet, still, there it is.

I meant the  error was gone in that reordering, even with mysqli_frree_result($stmt) present.

Anyway, got rid of it at the end.

Now, looks like this:

	//Query 'users' tbl for User's "Account Details". 
    $query_1 = "SELECT id,recruits_number,sponsor_username,account_activation_status,id_video_verification_status,id_verification_video_file_url,username,password,primary_domain,primary_website_email,registering_country,registering_ip,registering_browser,registering_os,registering_isp,age_range FROM users WHERE $querying_column = ?"; 
    $stmt_1 = mysqli_prepare($conn,$query_1); 
    mysqli_stmt_bind_param($stmt_1,'s',$login_username_or_email_or_domain); 
    mysqli_stmt_execute($stmt_1); 
    //Check if User's details was successfully extracted or not from 'users' tbl. 
    if (!$stmt_1) 
    { 
        echo "ERROR 1: Sorry! Our system is currently experiencing a problem logging you in!"; 
        exit(); 
    } 
    else 
    { 
        $result_1 = mysqli_stmt_bind_result($stmt_1,$db_id,$db_recruits_number,$db_sponsor_username,$db_account_activation_status,$db_id_video_verification_status,$db_id_verification_video_file_url,$db_username,$db_password,$db_primary_domain,$db_website_email,$db_registering_country,$registering_ip,$registering_browser,$registering_os,$registering_isp,$db_age_range); 
        mysqli_stmt_fetch($stmt_1); 
        mysqli_stmt_close($stmt_1); 
    } 
    if (!password_verify($login_password,$db_password)) 
    { 
        echo "Incorrect log-in details"; 
    } 
    else 
    { 
        //Query 'details_personal' tbl for User's "Personal Details". 
        $query_2 = "SELECT title,first_name,middle_name,surname,gender,date_of_birth,skin_complexion,height,weight,sexual_orientation,religion,education,profession,marital_status,working_status,country_of_birth,bio FROM details_personal WHERE username = ?"; 
        $stmt_2 = mysqli_prepare($conn,$query_2); 
        mysqli_stmt_bind_param($stmt_2,'s',$db_username); 
        mysqli_stmt_execute($stmt_2); 
        //Check if User's details was successfully extracted or not from 'details_personal' tbl. 
        if (!$stmt_2) 
        { 
            echo "ERROR 2: Sorry! Our system is currently experiencing a problem logging you in!"; 
            exit(); 
        } 
        else 
        {     
            $result_2 = mysqli_stmt_bind_result($stmt_2,$db_title,$db_first_name,$db_middle_name,$db_surname,$db_gender,$db_date_of_birth,$db_skin_complexion,$db_height,$db_weight,$db_sexual_orientation,$db_religion,$db_education,$db_profession,$db_marital_status,$db_working_status,$db_country_of_birth,$db_bio); 
            mysqli_stmt_fetch($stmt_2); 
            mysqli_stmt_close($stmt_2);             
        } 
        
        //Query 'details_contact_home' tbl for User's "Home Contact Details". 
        $query_3 = "SELECT personal_blog,personal_email,personal_mobile,home_land_line_phone,home_fax,home_zip,home_town,home_neighbourhood,home_borough,home_city,home_district,home_county,home_region,home_state,home_country FROM details_contact_home WHERE username = ?"; 
        $stmt_3 = mysqli_prepare($conn,$query_3); 
        mysqli_stmt_bind_param($stmt_3,'s',$db_username); 
        mysqli_stmt_execute($stmt_3); 
        //Check if User's details was successfully extracted or not from 'details_contact_home' tbl. 
        if (!$stmt_3) 
        { 
            echo "ERROR 3: Sorry! Our system is currently experiencing a problem logging you in!"; 
            exit(); 
        } 
        else 
        { 
            $result_3 = mysqli_stmt_bind_result($stmt_3,$db_persona_blog,$db_personal_email,$db_personal_mobile,$db_home_land_line_phone,$db_home_fax,$db_home_zip,$db_home_town,$db_home_neighbourhood,$db_home_borough,$db_home_city,$db_home_district,$db_home_county,$db_home_region,$db_home_state,$db_home_country);     
            mysqli_stmt_fetch($stmt_3); 
            mysqli_stmt_close($stmt_3); 
        } 
        
        //Query 'details_contact_business' tbl for User's "Business Contact Details". 
        $query_4 = "SELECT business_blog,business_name,business_email,business_mobile,business_land_line_phone,business_fax,business_zip,business_town,business_neighbourhood,business_borough,business_city,business_district,business_county,business_region,business_state,business_country FROM details_contact_business WHERE username = ?"; 
        $stmt_4 = mysqli_prepare($conn,$query_4); 
        mysqli_stmt_bind_param($stmt_4,'s',$db_username); 
        mysqli_stmt_execute($stmt_4); 
        //Check if User's details was successfully extracted or not from 'details_contact_business' tbl. 
        if (!$stmt_4) 
        { 
            echo "ERROR 4: Sorry! Our system is currently experiencing a problem logging you in!"; 
            exit(); 
        } 
        else 
        { 
            $result_4 = mysqli_stmt_bind_result($stmt_4,$db_business_blog,$db_business_name,$db_business_email,$db_business_mobile,$db_business_land_line_phone,$db_business_fax,$db_business_zip,$db_business_town,$db_business_neighbourhood,$db_business_borough,$db_business_city,$db_business_district,$db_business_county,$db_business_region,$db_business_state,$db_business_country);     
            mysqli_stmt_fetch($stmt_4); 
            mysqli_stmt_close($stmt_4);             
        } 
	

Also, look what Mc Guyver said:

"since you only use mysqli_stmt_free_result() if you are using mysqli_stmt_store_result(), which you aren't in the posted code, doesn't that mean that you shouldn't be using mysqli_stmt_free_result() at all?"

I missed the underline part and read it as:

"since you only use mysqli_stmt_free_result() if you are using mysqli_stmt_store_result(), which you aren't in the posted code, doesn't mean that you shouldn't be using mysqli_stmt_free_result() at all?"

Hence, I thought he was contradicting Requinix.

Nevermind. Already fixed it anyway.

Thanks!

Edited by phpsane

Share this post


Link to post
Share on other sites

Regardless of that interpretation, the manual makes it clear what it does and when to use it, and you claim to have read that.

Share this post


Link to post
Share on other sites
17 minutes ago, Barand said:

Regardless of that interpretation, the manual makes it clear what it does and when to use it, and you claim to have read that.

Rushed and read this part only half the night ago:

"mysqli_stmt::free_result -- mysqli_stmt_free_result  Frees stored result memory for the given statement handle"

Missed the part at the bottom which I spotted just now:

"Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().".

Got too many things to finish before fri sunset as I want to complete my 22mnths membership script project. 22 mnths! I thought originally, it would take 3mnths to complete.

Do yourself a favour: Close this thread. It has helped me rid an unncessary line out of my project script. ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.