Viewed   220 times

This is my code. I am checking if a user exists or not in a login/registration system:

public function userExist($email){
    $stmt = $this->conn->prepare("select email from users where email= ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows>0){

    }
    else{

    }
}

Can I use get_result instead of store_result() ?

 Answers

1

It depends on how you plan to read the result set. But in the actual example you have given, you are not interested in reading any returned data. The only thing that interests you is whether there is a record or not.

In that case your code is fine, but it would work equally well with get_result.

The difference becomes more apparent, when you want to get for example the userid of the user with the given email:

SELECT id FROM users WHERE email = ?

If you plan to read out that id with $stmt->fetch, then you would stick to store_result, and would use bind_result to define in which variable you want to get this id, like this:

$stmt->store_result();    
$stmt->bind_result($userid);  // number of arguments must match columns in SELECT
if($stmt->num_rows > 0) {
    while ($stmt->fetch()) {
        echo $userid;  
    }
}

If you prefer to get a result object on which you can call fetch_assoc() or any of the fetch_* variant methods, then you need to use get_result, like this:

$result = $stmt->get_result();   // You get a result object now
if($result->num_rows > 0) {     // Note: change to $result->...!
    while ($data = $result->fetch_assoc()) {
        echo $data['id'];
    }
}

Note that you get a result object from get_result, which is not the case with store_result. You should get num_rows from that result object now.

Both ways work, and it is really a matter of personal preference.

Saturday, November 19, 2022
1

I went ahead and ran a test where one query uses a prepared statement, and the other builds the entire query then executes that. I'm probably not making what I'm wanting to know easy to understand.

Here's my test code. I was thinking prepared statements sort of held back execution until a $stmt->close() was called to optimize it or something. That doesn't appear to be the case though as the test that builds the query using real_escape_string is at least 10 times faster.

<?php

$db = new mysqli('localhost', 'user', 'pass', 'test');

$start = microtime(true);
$a = 'a';
$b = 'b';

$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)');
$sql->bind_param('ss', $a, $b);
for($i = 0; $i < 10000; $i++)
{
    $a = chr($i % 1);
    $b = chr($i % 2);
    $sql->execute();
}
$sql->close();

echo microtime(true) - $start;

$db->close();

?>
Sunday, November 6, 2022
1

This actually depends on the Mysql server. The default max size for all data combined in the entire query is 1mb. See: http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

If your data combined is under that "max_allowed_packet" threshold, just use "s" for the binding type for any text field. Infact, you can usually get away with using "s" for any field type at all (date, float, etc).

If your entire entry combined that you want to insert is over 1mb (or whatever you reset it to) in length, you'll want to use mysqli_stmt::send_long_data method and the "b" binding type to send this particular field in chunks.

Wednesday, August 24, 2022
 
2

The PHP Language reference has details on what a function and class is: http://www.php.net/manual/en/langref.php

It also explains most the other features of PHP. If want to learn PHP that is the best place to start.

Functions

The function is a grouping of statements (lines of code).

For example the following statements:

$name = 'mary';
$gender = 'girl';
if ($gender == 'girl') {
  $line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
  $line = $name . ' had a little horse.';
}
echo $line;

Can be grouped together into a function so it can be reused:

getSentence('mary', 'girl');
getSentence('peter', 'boy');
function getSentence($name, $gender) {
  if ($gender == 'girl') {
    $line = $name . ' had a little pony.';
  } else if ($gender == 'boy') {
    $line = $name . ' had a little horse.';
  }
  echo $line;
}

Notice the two function calls:

getSentence('mary', 'girl');
getSentence('peter', 'boy');

These two statements run the whole block of code inside the getSentence function and pass it the variables $name and $gender. With the first function $name = 'mary' and $gender = 'girl' and in the second $name = 'peter' and $gender = 'boy'.

So the main benefit of functions is that you have grouped code for reuse, allowing the passing of different values for the variables needed by the function. These variables are called the function parameters.

Another benefit of having the code grouped is easier readability. You are essentially naming the block of code, and giving them a specific purpose. Making it easy to read and remember it's use.

Another benefit is that redundancy is removed. You do not have to write the block of code more then once. You just define it once, and call it multiple times. This also makes editing of the function code affect all calls to that function - which reduces errors in having to edit multiple locations when changing just one aspect.

eg:

We can make sure the $name string has an uppercase first character.

function getSentence($name, $gender) {
  $name = ucfirst($name);
  if ($gender == 'girl') {
    $line = $name . ' had a little pony.';
  } else if ($gender == 'boy') {
    $line = $name . ' had a little horse.';
  }
  echo $line;
}

We made just one change, and it affected every function call to getSentence(). In this case both:

getSentence('mary', 'girl'); 

and

getSentence('peter', 'boy'); 

Classes are a grouping of functions.

class Play {
  function getSentence($name, $gender) {
    $name = ucfirst($name);
    if ($gender == 'girl') {
      $line = $name . ' had a little pony.';
    } else if ($gender == 'boy') {
      $line = $name . ' had a little horse.';
    }
    echo $line;
  }
  function getSong($name) {
    // code here
  }
}

All we did was put

class Play { /** functions here **/ }

around a group of functions.

This offers the same benefits that functions do for statements except classes does it for functions.

Classes go further to build a programming methodology called Object Oriented programming (OOP), which you can read more about in link to PHP Language reference.

This defines classes as the template or definition of Objects. Objects being similar to real world objects, with the functions being called "methods" that can be called for the object.

So the class Play can be thought of as the object called "Play" with the methods "getSentence" and "getSong". These methods can then manipulate the properties of the object "Play" or return useful information about "Play". In this way, all the code inside Play becomes independent of code elsewhere in the program.

When the code inside Play requires some code elsewhere to function, it can be brought in using "inheritance", which is a major part of OOP. I will not go into detail about this as it is a very broad topic.

I would recommend getting a book on OOP and reading it to really understand why you should use classes and methods and when to use them.

Monday, October 10, 2022
 
bgies
 
4

To validate is to make sure that the input matches your business rules. If it doesn't, you reject the input. You could be expecting user to provide you a number but if you receive something that's not a number, then that's a validation error.

Whereas sanitizing means to ensure that the format of the input doesn't break its container. This could be a semicolon(;) mistakenly added to the input by the user so you remove/escape it for him when it gets sent to you. Sanitization is also used to escape any attempt to cause data corruption when dealing with database based on user input.

Monday, December 26, 2022
 
ha22109
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :