Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

WikiQuora

WikiQuora Logo WikiQuora Logo

WikiQuora Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
Home/php

WikiQuora Latest Questions

W3spoint99
  • 0
W3spoint99Begginer
Asked: January 6, 2025In: PHP

How to delete an element from an array in PHP?

  • 0

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element? I thought that setting it to null would do it, but apparently it does not work.

arraydeleteelementhowphpunset
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 6, 2025 at 2:58 pm

    There are different ways to delete an array element, where some are more useful for some specific tasks than others. Deleting a Single Array Element If you want to delete just one single array element you can use unset() and alternatively array_splice(). By key or by value? If you know the value andRead more

    There are different ways to delete an array element, where some are more useful for some specific tasks than others.

    Deleting a Single Array Element

    If you want to delete just one single array element you can use unset() and alternatively array_splice().

    By key or by value?

    If you know the value and don’t know the key to delete the element you can use array_search() to get the key. This only works if the element doesn’t occur more than once, since array_search() returns the first hit only.

    unset() Expression

    Note: When you use unset() the array keys won’t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0 (the array remains a list).

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    unset($array[1]);
              // ↑ Key of element to delete
    

    Example Output:

    [
        [0] => a
        [2] => c
    ]
    

    array_splice() Function

    If you use array_splice() the (integer) keys will automatically be reindex-ed, but the associative (string) keys won’t change — as opposed to array_values() after unset(), which will convert all keys to numerical keys.

    Note: array_splice() needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    array_splice($array, 1, 1);
                      // ↑ Offset of element to delete
    

    Example Output:

    [
        [0] => a
        [1] => c
    ]
    

    array_splice(), same as unset(), take the array by reference. You don’t assign the return values back to the array.

    Deleting Multiple Array Elements

    If you want to delete multiple array elements and don’t want to call unset() or array_splice() multiple times you can use the functions array_diff() or array_diff_key() depending on whether you know the values or the keys of the elements to remove from the array.

    array_diff() Function

    If you know the values of the array elements which you want to delete, then you can use array_diff(). As before with unset() it won’t change the keys of the array.

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
    $array = array_diff($array, ["a", "c"]);
                             // └────────┘
                             // Array values to delete
    

    Example Output:

    [
        [1] => b
    ]
    

    array_diff_key() Function

    If you know the keys of the elements which you want to delete, then you want to use array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                                  // ↑           ↑
                                  // Array keys of elements to delete
    

    Example Output:

    [
        [1] => b
    ]
    

    If you want to use unset() or array_splice() to delete multiple elements with the same value you can use array_keys() to get all the keys for a specific value and then delete all elements.

    array_filter() Function

    If you want to delete all elements with a specific value in the array you can use array_filter().

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = array_filter($array, static function ($element) {
        return $element !== "b";
        //                   ↑
        // Array value which you want to delete
    });
    

    Example Output:

    [
        [0] => a
        [2] => c
    ]
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 308 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: January 6, 2025In: PHP

Why to not use mysql_* functions in PHP?

  • 0

What are the technical reasons for why one shouldn’t use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())? Why should I use something else even if they work on my site? If they don’t work on my site, why do I get errors like Warning: mysql_connect(): No such file or ...

functionsmysqlphp
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 6, 2025 at 2:58 pm
    This answer was edited.

    PHP offers three different APIs to connect to MySQL. These are the mysql(removed as of PHP 7), mysqli, and PDO extensions. The mysql_* functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating usersRead more

    PHP offers three different APIs to connect to MySQL. These are the mysql(removed as of PHP 7), mysqli, and PDO extensions.

    The mysql_* functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating users to move away from the commonly used ext/mysql extension is part of this (check php.internals: deprecating ext/mysql).

    And the later PHP developer team has taken the decision to generate E_DEPRECATED errors when users connect to MySQL, whether through mysql_connect(), mysql_pconnect() or the implicit connection functionality built into ext/mysql.

    ext/mysql was officially deprecated as of PHP 5.5 and has been removed as of PHP 7.

    See the Red Box?

    When you go on any mysql_* function manual page, you see a red box, explaining it should not be used anymore.

    Why


    Moving away from ext/mysql is not only about security, but also about having access to all the features of the MySQL database.

    ext/mysql was built for MySQL 3.23 and only got very few additions since then while mostly keeping compatibility with this old version which makes the code a bit harder to maintain. Missing features that is not supported by ext/mysql include: (from PHP manual).

    • Stored procedures (can’t handle multiple result sets)
    • Prepared statements
    • Encryption (SSL)
    • Compression
    • Full Charset support

    Reason to not use mysql_* function:

    • Not under active development
    • Removed as of PHP 7
    • Lacks an OO interface
    • Doesn’t support non-blocking, asynchronous queries
    • Doesn’t support prepared statements or parameterized queries
    • Doesn’t support stored procedures
    • Doesn’t support multiple statements
    • Doesn’t support transactions
    • Doesn’t support all of the functionality in MySQL 5.1

    Above point quoted from Quentin’s answer

    Lack of support for prepared statements is particularly important as they provide a clearer, less error prone method of escaping and quoting external data than manually escaping it with a separate function call.

    See the comparison of SQL extensions.


    Suppressing deprecation warnings

    While code is being converted to MySQLi/PDO, E_DEPRECATED errors can be suppressed by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    Note that this will also hide other deprecation warnings, which, however, may be for things other than MySQL. (from PHP manual)

    The article PDO vs. MySQLi: Which Should You Use? by Dejan Marjanovic will help you to choose.

    And a better way is PDO, and I am now writing a simple PDO tutorial.


    A simple and short PDO tutorial


    Q. First question in my mind was: what is `PDO`?

    A. “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”

    alt text


    Connecting to MySQL

    With mysql_* function or we can say it the old way (deprecated in PHP 5.5 and above)

    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testdb', $link);
    mysql_set_charset('UTF-8', $link);
    

    With PDO: All you need to do is create a new PDO object. The constructor accepts parameters for specifying the database source PDO‘s constructor mostly takes four parameters which are DSN (data source name) and optionally username, password.

    Here I think you are familiar with all except DSN; this is new in PDO. A DSN is basically a string of options that tell PDO which driver to use, and connection details. For further reference, check PDO MySQL DSN.

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
    

    Note: you can also use charset=UTF-8, but sometimes it causes an error, so it’s better to use utf8.

    If there is any connection error, it will throw a PDOException object that can be caught to handle Exception further.

    Good read: Connections and Connection management ¶

    You can also pass in several driver options as an array to the fourth parameter. I recommend passing the parameter which puts PDO into exception mode. Because some PDO drivers don’t support native prepared statements, so PDO performs emulation of the prepare. It also lets you manually enable this emulation. To use the native server-side prepared statements, you should explicitly set it false.

    The other is to turn off prepare emulation which is enabled in the MySQL driver by default, but prepare emulation should be turned off to use PDO safely.

    I will later explain why prepare emulation should be turned off. To find reason please check this post.

    It is only usable if you are using an old version of MySQL which I do not recommended.

    Below is an example of how you can do it:

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
                  'username', 
                  'password',
                  array(PDO::ATTR_EMULATE_PREPARES => false,
                  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    

    Can we set attributes after PDO construction?

    Yes, we can also set some attributes after PDO construction with the setAttribute method:

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
                  'username', 
                  'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    

    Error Handling


    Error handling is much easier in PDO than mysql_*.

    A common practice when using mysql_* is:

    //Connected to MySQL
    $result = mysql_query("SELECT * FROM table", $link) or die(mysql_error($link));
    

    OR die() is not a good way to handle the error since we can not handle the thing in die. It will just end the script abruptly and then echo the error to the screen which you usually do NOT want to show to your end users, and let bloody hackers discover your schema. Alternately, the return values of mysql_* functions can often be used in conjunction with mysql_error() to handle errors.

    PDO offers a better solution: exceptions. Anything we do with PDO should be wrapped in a try–catch block. We can force PDO into one of three error modes by setting the error mode attribute. Three error handling modes are below.

    • PDO::ERRMODE_SILENT. It’s just setting error codes and acts pretty much the same as mysql_* where you must check each result and then look at $db->errorInfo(); to get the error details.
    • PDO::ERRMODE_WARNING Raise E_WARNING. (Run-time warnings (non-fatal errors). Execution of the script is not halted.)
    • PDO::ERRMODE_EXCEPTION: Throw exceptions. It represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about exceptions in PHP. It acts very much like or die(mysql_error());, when it isn’t caught. But unlike or die(), the PDOException can be caught and handled gracefully if you choose to do so.

    Good read:

    • Errors and error handling ¶
    • The PDOException class ¶
    • Exceptions ¶

    Like:

    $stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
    $stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    

    And you can wrap it in try–catch, like below:

    try {
        //Connect as appropriate as above
        $db->query('hi'); //Invalid query!
    } 
    catch (PDOException $ex) {
        echo "An Error occured!"; //User friendly message/message you want to show to user
        some_logging_function($ex->getMessage());
    }
    

    You do not have to handle with try–catch right now. You can catch it at any time appropriate, but I strongly recommend you to use try–catch. Also it may make more sense to catch it at outside the function that calls the PDO stuff:

    function data_fun($db) {
        $stmt = $db->query("SELECT * FROM table");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    //Then later
    try {
        data_fun($db);
    }
    catch(PDOException $ex) {
        //Here you can handle error and show message/perform action you want.
    }
    

    Also, you can handle by or die() or we can say like mysql_*, but it will be really varied. You can hide the dangerous error messages in production by turning display_errors off and just reading your error log.

    Now, after reading all the things above, you are probably thinking: what the heck is that when I just want to start leaning simple SELECT, INSERT, UPDATE, or DELETE statements? Don’t worry, here we go:


    Selecting Data

    PDO select image

    So what you are doing in mysql_* is:

    <?php
    $result = mysql_query('SELECT * from table') or die(mysql_error());
    
    $num_rows = mysql_num_rows($result);
    
    while($row = mysql_fetch_assoc($result)) {
        echo $row['field1'];
    }
    

    Now in PDO, you can do this like:

    <?php
    $stmt = $db->query('SELECT * FROM table');
    
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['field1'];
    }
    

    Or

    <?php
    $stmt = $db->query('SELECT * FROM table');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    //Use $results
    

    Note: If you are using the method like below (query()), this method returns a PDOStatement object. So if you want to fetch the result, use it like above.

    <?php
    foreach($db->query('SELECT * FROM table') as $row) {
        echo $row['field1'];
    }
    

    In PDO Data, it is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, the best approach would be telling PDO how you’d like the data to be fetched. In the below section I am explaining this.

    Fetch Modes

    Note the use of PDO::FETCH_ASSOC in the fetch() and fetchAll() code above. This tells PDO to return the rows as an associative array with the field names as keys. There are many other fetch modes too which I will explain one by one.

    First of all, I explain how to select fetch mode:

     $stmt->fetch(PDO::FETCH_ASSOC)
    

    In the above, I have been using fetch(). You can also use:

    • PDOStatement::fetchAll() – Returns an array containing all of the result set rows
    • PDOStatement::fetchColumn() – Returns a single column from the next row of a result set
    • PDOStatement::fetchObject() – Fetches the next row and returns it as an object.
    • PDOStatement::setFetchMode() – Set the default fetch mode for this statement

    Now I come to fetch mode:

    • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
    • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

    There are even more choices! Read about them all in PDOStatement Fetch documentation..

    Getting the row count:

    Instead of using mysql_num_rows to get the number of returned rows, you can get a PDOStatement and do rowCount(), like:

    <?php
    $stmt = $db->query('SELECT * FROM table');
    $row_count = $stmt->rowCount();
    echo $row_count.' rows selected';
    

    Getting the Last Inserted ID

    <?php
    $result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
    $insertId = $db->lastInsertId();
    

    Insert and Update or Delete statements

    Insert and update PDO image

    What we are doing in mysql_* function is:

    <?php
    $results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());
    echo mysql_affected_rows($result);
    

    And in pdo, this same thing can be done by:

    <?php
    $affected_rows = $db->exec("UPDATE table SET field='value'");
    echo $affected_rows;
    

    In the above query PDO::exec execute an SQL statement and returns the number of affected rows.

    Insert and delete will be covered later.

    The above method is only useful when you are not using variable in query. But when you need to use a variable in a query, do not ever ever try like the above and there for prepared statement or parameterized statement is.


    Prepared Statements

    Q. What is a prepared statement and why do I need them?
    A. A prepared statement is a pre-compiled SQL statement that can be executed multiple times by sending only the data to the server.

    The typical workflow of using a prepared statement is as follows (quoted from Wikipedia three 3 point):

    1. Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled ? below):
    `INSERT INTO PRODUCT (name, price) VALUES (?, ?)`
    
    1. The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.
    2. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result). The application may execute the statement as many times as it wants with different values. In this example, it might supply ‘Bread’ for the first parameter and 1.00 for the second parameter.

    You can use a prepared statement by including placeholders in your SQL. There are basically three ones without placeholders (don’t try this with variable its above one), one with unnamed placeholders, and one with named placeholders.

    Q. So now, what are named placeholders and how do I use them?
    A. Named placeholders. Use descriptive names preceded by a colon, instead of question marks. We don’t care about position/order of value in name place holder:

     $stmt->bindParam(':bla', $bla);
    

    bindParam(parameter,variable,data_type,length,driver_options)

    You can also bind using an execute array as well:

    <?php
    $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
    $stmt->execute(array(':name' => $name, ':id' => $id));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    

    Another nice feature for OOP friends is that named placeholders have the ability to insert objects directly into your database, assuming the properties match the named fields. For example:

    class person {
        public $name;
        public $add;
        function __construct($a,$b) {
            $this->name = $a;
            $this->add = $b;
        }
    
    }
    $demo = new person('john','29 bla district');
    $stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)");
    $stmt->execute((array)$demo);
    

    Q. So now, what are unnamed placeholders and how do I use them?
    A. Let’s have an example:

    <?php
    $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
    $stmt->bindValue(1, $name, PDO::PARAM_STR);
    $stmt->bindValue(2, $add, PDO::PARAM_STR);
    $stmt->execute();
    

    and

    $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
    $stmt->execute(array('john', '29 bla district'));
    

    In the above, you can see those ? instead of a name like in a name place holder. Now in the first example, we assign variables to the various placeholders ($stmt->bindValue(1, $name, PDO::PARAM_STR);). Then, we assign values to those placeholders and execute the statement. In the second example, the first array element goes to the first ? and the second to the second ?.

    NOTE: In unnamed placeholders we must take care of the proper order of the elements in the array that we are passing to the PDOStatement::execute() method.


    SELECT, INSERT, UPDATE, DELETE prepared queries

    1. SELECT:

      $stmt = $db->prepare(“SELECT * FROM table WHERE id=:id AND name=:name”); $stmt->execute(array(‘:name’ => $name, ‘:id’ => $id)); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    2. INSERT:

      $stmt = $db->prepare(“INSERT INTO table(field1,field2) VALUES(:field1,:field2)”); $stmt->execute(array(‘:field1’ => $field1, ‘:field2’ => $field2)); $affected_rows = $stmt->rowCount();

    3. DELETE:

      $stmt = $db->prepare(“DELETE FROM table WHERE id=:id”); $stmt->bindValue(‘:id’, $id, PDO::PARAM_STR); $stmt->execute(); $affected_rows = $stmt->rowCount();

    4. UPDATE:

      $stmt = $db->prepare(“UPDATE table SET name=? WHERE id=?”); $stmt->execute(array($name, $id)); $affected_rows = $stmt->rowCount();


    NOTE:

    However PDO and/or MySQLi are not completely safe. Check the answer Are PDO prepared statements sufficient to prevent SQL injection? by ircmaxell. Also, I am quoting some part from his answer:

    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $pdo->query('SET NAMES GBK');
    $stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1");
    $stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 289 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: December 25, 2024In: Programmers

How to prevent SQL injection in PHP?

  • 0

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That’s because the user can input something ...

mysqlphpsecuritysqlsql-injection
  1. Saralyn
    Saralyn Teacher
    Added an answer on December 25, 2024 at 10:08 am

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fulRead more

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

    You basically have two options to achieve this:

    1. Using PDO (for any supported database driver):
      $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
      $stmt->execute([ 'name' => $name ]);
      
      foreach ($stmt as $row) {
          // Do something with $row
      }
      
    2. Using MySQLi (for MySQL):
      Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:

      $result = $db->execute_query('SELECT * FROM users WHERE name = ?', [$name]);
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

      Up to PHP8.1:

      $stmt = $db->prepare('SELECT * FROM employees WHERE name = ?');
      $stmt->bind_param('s', $name); // 's' specifies variable type 'string'
      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

    If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.


    Correctly setting up the connection

    PDO

    Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

    $dsn = 'mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4';
    $dbConnection = new PDO($dsn, 'user', 'password');
    
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    In the above example, the error mode isn’t strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

    What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

    Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

    Mysqli

    For mysqli we have to follow the same routine:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
    $dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
    $dbConnection->set_charset('utf8mb4'); // charset
    

    Explanation

    The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

    The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

    Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

    Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

    Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

    $stmt = $db->prepare('INSERT INTO table (column) VALUES (:column)');
    $stmt->execute(['column' => $value]);
    

    Can prepared statements be used for dynamic queries?

    While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

    For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

    // Value whitelist
    // $dir can only be 'DESC', otherwise it will be 'ASC'
    if (empty($dir) || $dir !== 'DESC') {
       $dir = 'ASC';
    }
    
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 469 Views
Answer

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is the difference between Promises and Observables?

    • 2 Answers
  • W3spoint99

    Can't bind to 'ngModel' since it isn't a known property ...

    • 2 Answers
  • W3spoint99

    How to prevent SQL injection in PHP?

    • 1 Answer
  • Saralyn
    Saralyn added an answer Learn Java if: ✅ You want to work on enterprise applications.… April 27, 2025 at 2:01 pm
  • Saralyn
    Saralyn added an answer AI is getting smarter, but replacing programmers entirely? That’s not… April 27, 2025 at 1:58 pm
  • Saralyn
    Saralyn added an answer Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature… January 17, 2025 at 2:03 pm

Trending Tags

AI angular application.properties arrays artificial intelligence coding how Java javascript machine learning mysql nullpointerexception php programmer python reactjs spring springboot sql string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved