Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times.
For example:
<?php
$connection=mysqli_connect("localhost","username","password","db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValue( $val ){
mysqli_query($connection,"INSERT INTO table_name (integerValue) VALUES ( $value )");
}
for( $i =0; $i<99; $i++){
// Calling function to execute query one by one
insertValue( $i );
}
// Closing the connection as best practice
mysqli_close($connection);
?>
The script above is much slower.
So, script below is the best solution to run fast:
<?php
$connection=mysqli_connect("localhost","username","password","db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValues( $val ){
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO table_name(integerValue) VALUES .implode(',', $value)";
mysqli_query($connection, $query);
}
$data_array = array();
for( $i =0; $i<99; $i++){
// Creating an array of data to be inserted.
$data_array[ ] = '(" ' . $i. '")' ;
}
// Inserting the data in a single call
insertValues( $data_array );
// Closing the connection as a best practice
mysqli_close($connection);
?>
For example:
<?php
$connection=mysqli_connect("localhost","username","password","db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValue( $val ){
mysqli_query($connection,"INSERT INTO table_name (integerValue) VALUES ( $value )");
}
for( $i =0; $i<99; $i++){
// Calling function to execute query one by one
insertValue( $i );
}
// Closing the connection as best practice
mysqli_close($connection);
?>
The script above is much slower.
So, script below is the best solution to run fast:
<?php
$connection=mysqli_connect("localhost","username","password","db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValues( $val ){
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO table_name(integerValue) VALUES .implode(',', $value)";
mysqli_query($connection, $query);
}
$data_array = array();
for( $i =0; $i<99; $i++){
// Creating an array of data to be inserted.
$data_array[ ] = '(" ' . $i. '")' ;
}
// Inserting the data in a single call
insertValues( $data_array );
// Closing the connection as a best practice
mysqli_close($connection);
?>
No comments:
Post a Comment