Fictional member order guest php. Basics of working with PHP MySqli. Deleting old entries

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
  • The parameters to prepared statements don"t need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don"t support them. This ensures that an application will be able to use the same data access paradigm regardless of the capabilities of the database.

Example #1 Repeated inserts using prepared statements

name and a value for the named placeholders.

$stmt = $dbh -> prepare ( "INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt -> bindParam (":name" , $name );
$stmt -> bindParam (":value" , ​​$value );

// insert one row
$name = "one" ;
$value = 1 ;
$stmt -> execute();

$name = "two" ;
$value = 2 ;
$stmt -> execute();
?>

Example #2 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

$stmt = $dbh -> prepare ( "INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt -> bindParam(1, $name);
$stmt -> bindParam (2 , $value );

// insert one row
$name = "one" ;
$value = 1 ;
$stmt -> execute();

// insert another row with different values
$name = "two" ;
$value = 2 ;
$stmt -> execute();
?>

Example #3 Fetching data using prepared statements

Example #4 Calling a stored procedure with an output parameter

If the database driver supports it, an application may also bind parameters for output as well as input. Output parameters are typically used to retrieve values ​​from stored procedures. Output parameters are slightly more complex to use than input parameters, in that a developer must know how large a given parameter might be when they bind it. If the value turns out to be larger than the size they suggested, an error is raised.

$stmt = $dbh -> prepare ("CALL sp_returns_string(?)" );
$stmt -> bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// call the stored procedure
$stmt -> execute();

print "procedure returned $return_value \n" ;
?>

Example #5 Calling a stored procedure with an input/output parameter

Developers may also specify parameters that hold values ​​both input and output;

$stmt = $dbh -> prepare ( the syntax is similar to output parameters. In this next example, the string "hello" is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.);
"CALL sp_takes_string_returns_string(?)"" ;!}
$value = "hello

// call the stored procedure
$stmt -> execute();

$stmt -> bindParam (1 , $value , PDO :: PARAM_STR | PDO :: PARAM_INPUT_OUTPUT , 4000 );
?>

print "procedure returned $value \n" ; Due to discontinuation of support PHP MySQL in 2011, PDO or MySqli

. They have better functionality (than MySQL) and offer an OOP (Object Oriented Interface) API. Which one is better is a topic for another article, in this article we will try to understand the basics of working with MySqli. Therefore, without further ado, let's move on to consider connecting, selecting, inserting, updating and deleting records (data/documents/information) using PHP MySqli. I hope that this article will be useful in solving problems that may arise when working with PHP MySqli.

Installing MySqli Using PHP versions 5.3.0+, MySqli is available by default; for older versions, to make it available, you need to include the php_mysqli.dll DLL inside the file php.ini and edit php.ini by uncommenting the line extension=php_mysqli.dll. On Linux, MySQLIi will be installed automatically when you install the PHP5 mysql package. More detailed information about installation in windows systems

and linux can be found.

MySqli offers two ways to connect to a database: procedural and object-oriented. It is recommended to use object-oriented. Procedural is similar to (old) MySql, so it may be preferable for newbies, but it's worth remembering that it's not recommended.

PHP

//procedural style $mysqli = mysqli_connect("host","username","password","database_name"); //object-oriented style (recommended) $mysqli = new mysqli("host","username","password","database_name");

The following shows how to open a connection to a database in an object-oriented manner. This method will be used in all the examples below.

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) ?>

Selecting (SELECT) the resulting series as an associative array

mysqli_fetch_assoc() : The code below fetches the result series as associative array. The returned array contains rows retrieved from the database, where the column names will be the key used to access the internal data. As shown below, the data is displayed as an HTML table.

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) //MySqli Select Query $results = $mysqli-> "; while($row = $results->fetch_assoc()) ( print " "; print " "; print " "; print " "; print " "; print " "; print ""; ) print "
".$row["id"]."".$row["product_code"]."".$row["product_name"]."".$row["product_desc"]."".$row["price"]."
"; // Frees the memory associated with a result $results->free(); // close connection $mysqli->close(); ?>

Selecting (SELECT) the resulting series as an array (associative, regular, or both)

fetch_array() function: returns an array with the combined functionality of mysqli_fetch_row and mysqli_fetch assoc. This function is an extended version of the mysqli_fetch_row() function; You can use either a string or numbers to access data.

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) //MySqli Select Query $results = $mysqli->query("SELECT id, product_code, product_desc , price FROM products"); print " fetch_array()) ( print " "; print " "; print " "; print " "; print " "; print " "; print ""; ) print "
".$row["id"]."".$row["product_code"]."".$row["product_name"]."".$row["product_desc"]."".$row["price"]."
"; // Frees the memory associated with a result $results->free(); // close connection $mysqli->close(); ?>

Selecting (SELECT) the result series as an object

fetch_object() : To get the result set as an object, you need to use MySqli fetch_object() . The object's attributes will display the names of the fields found within the result set.

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) //MySqli Select Query $results = $mysqli->query("SELECT id, product_code, product_desc , price FROM products"); print " "; while($row = $results->fetch_object()) ( print " "; print " "; print " "; print " "; print " "; print " "; print ""; ) print "
".$row->id."".$row->product_code."".$row->product_name."".$row->product_desc."".$row->price."
"; // close connection $mysqli->close(); ?>

Selecting (SELECT) a single value

A single value can be retrieved from the database using fetch_object (Cameron Spear method).

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) //chained PHP functions $product_name = $mysqli->query("SELECT product_name FROM products WHERE id = 1")->fetch_object()->product_name; print $product_name; //output value $mysqli->close(); ?>

Retrieving (SELECT COUNT) the number of rows in the table

Sometimes you need to know the number of rows in a table, especially when numbering pages.

PHP

connect_error) ( die("Error: (". $mysqli->connect_errno .") ". $mysqli->connect_error); ) //get total number of records $results = $mysqli->query("SELECT COUNT(* ) FROM users"); $get_total_rows = $results->fetch_row(); //hold total records in variable $mysqli->close(); ?>

SELECT using prepared statements

prepared statements- a special DBMS tool that allows you to speed up the sequential execution of repeating queries built according to the same template.

One of the features of MySqli is the ability to use already written templates: that is, you only need to write a query once, after which it can be executed many times with different parameters. Using already written templates improves performance for large tables and complex queries. To prevent malicious code from entering, each request is analyzed separately by the server.

The code below uses a template (Prepared statement) to retrieve data from the database. Aggregate ? in an SQL query it acts as a marker and will be replaced by a parameter, which in turn can be a string, integer, double or blob. In our case, this is the string $search_product.

PHP

$search_product = "PD1001"; //product id //create a prepared statement $query = "SELECT id, product_code, product_desc, price FROM products WHERE product_code=?"; $statement = $mysqli->prepare($query); //bind parameters for markers, where (s = string, i = integer, d = double, b = blob) $statement->bind_param("s", $search_product); //execute query $statement->execute(); //bind result variables $statement-> "; //fetch records while($statement->fetch()) ( print " "; print " "; print " "; print " "; print " "; print ""; ) print "
".$id."".$product_code."".$product_desc."".$price."
"; //close connection $statement->close();

The same request with several parameters:

PHP

$search_ID = 1; $search_product = "PD1001"; $query = "SELECT id, product_code, product_desc, price FROM products WHERE ID=? AND product_code=?"; $statement = $mysqli->prepare($query); $statement->bind_param("is", $search_ID, $search_product); $statement->execute(); $statement->bind_result($id, $product_code, $product_desc, $price); print " "; while($statement->fetch()) ( print " "; print " "; print " "; print " "; print " "; print ""; ) print "
".$id."".$product_code."".$product_desc."".$price."
"; //close connection $statement->close();

INSERT a record

The entry below inserts a new row into the table.

PHP

real_escape_string("P1234")."""; $product_name = """.$mysqli->real_escape_string("42 inch TV")."""; $product_price = """.$mysqli->real_escape_string("600 ")."""; //MySqli Insert Query $insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)"); )( print "Success! ID of last inserted record is: " .$mysqli->insert_id ."
"; )else( die("Error: (". $mysqli->errno .") ". $mysqli->error); ) ?>

The excerpt below inserts the same meanings using Prepared Statements. As we've already said, patterns are extremely effective against SQL injection. For the example given, their use is the best option.

PHP

//values ​​to be inserted in database table $product_code = "P1234"; $product_name = "42 inch TV"; $product_price = "600"; $query = "INSERT INTO products (product_code, product_name, price) VALUES(?, ?, ?)"; $statement = $mysqli->prepare($query); //bind parameters for markers, where (s = string, i = integer, d = double, b = blob) $statement->bind_param("sss", $product_code, $product_name, $product_price); if($statement->execute())( print "Success! ID of last inserted record is: " .$statement->insert_id ."
"; )else( die("Error: (". $mysqli->errno .") ". $mysqli->error); ) $statement->close();

INSERT multiple records

Inserting multiple rows at once is done by including a row of column values, with each row of values ​​surrounded by parentheses and separated from the others by a comma. Sometimes you need to find out how many records were inserted, updated or deleted, you can use mysqli_affected_rows for this.

PHP

//product 1 $product_code1 = """.$mysqli->real_escape_string("P1")."""; $product_name1 = """.$mysqli->real_escape_string("Google Nexus")."""; $product_price1 = """.$mysqli->real_escape_string("149")."""; //product 2 $product_code2 = """.$mysqli->real_escape_string("P2")."""; $product_name2 = """.$mysqli->real_escape_string("Apple iPad 2")."""; $product_price2 = """.$mysqli->real_escape_string("217")."""; //product 3 $product_code3 = """.$mysqli->real_escape_string("P3")."""; $product_name3 = """.$mysqli->real_escape_string("Samsung Galaxy Note")."""; $product_price3 = """.$mysqli->real_escape_string("259")."""; //Insert multiple rows $insert = $mysqli->query("INSERT INTO products(product_code, product_name, price) VALUES ($product_code1, $product_name1, $product_price1), ($product_code2, $product_name2, $product_price2), ($ product_code3, $product_name3, $product_price3)"); if($insert)( //return total inserted records using mysqli_affected_rows print "Success! Total " .$mysqli->affected_rows ." rows added.
"; )else( die("Error: (". $mysqli->errno .") ". $mysqli->error); )

Update/Delete entries

The principle of updating and deleting records is the same. It is enough to replace the query string with MySql update or delete (I don’t understand, see for yourself).

PHP

//MySqli Update Query $results = $mysqli->query("UPDATE products SET product_name="52 inch TV", product_code="323343" WHERE ID=24"); //MySqli Delete Query //$results = $mysqli->query("DELETE FROM products WHERE ID=24"); if($results)( print "Success! record updated / deleted"; )else( print "Error: (". $mysqli->errno .") ". $mysqli->error; )

Update using prepared statements

An example of updating a record using prepared statements is shown below.

PHP

$product_name = "52 inch TV"; $product_code = "9879798"; $find_id = 24; $query = "UPDATE products SET product_name=?, product_code=? WHERE ID=?"; $statement = $mysqli->prepare($query); //bind parameters for markers, where (s = string, i = integer, d = double, b = blob) $results = $statement->bind_param("ssi", $product_name, $product_code, $find_id); if($results)( print "Success! record updated"; )else( print "Error: (". $mysqli->errno .") ". $mysqli->error; )

Deleting old entries

All records that have been on the server for more than 1 day are deleted; You can set the number of days yourself.

PHP

//MySqli Delete Query $results = $mysqli- (NOW() - INTERVAL 1 DAY)"); if($results)( print "Success! deleted one day old records"; )else( print "Error: (". $mysqli- Conclusion

Without a doubt, MySqli is significantly better than the standard MySql PHP extension, although the principles of their operation are quite similar. I hope the above information is helpful when creating and migrating projects in the future. For convenience, the opportunity to download example files has been implemented below. This can be done by clicking on the download button.



2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.