Showing posts with label mysqli. Show all posts
Showing posts with label mysqli. Show all posts

Wednesday, October 21, 2020

Mysql data get and show in google sheet




Step 1: Create a spreadsheet within your Google Drive.

Step 2: Insert script in newly created spreadsheet.


Step 3.1: To insert the script in Google spreadsheet go to Tools > Script Editor.

Step 4.2: On opening script editor you will find a Google Apps Script pop-up Close it.


Step 5: save file and run the script


 // Replace the variables in this block with real values.

    var address = '192.xxxxx';

    var user = 'xxxxx';

    var userPwd = 'xxxxx@@121';

    var db = 'xxxxx';

    var dbUrl = 'jdbc:mysql://' + address + '/' + db;


    // Read up to 1000 rows of data from the table and log them.

   function readFromTable() {

      var conn = Jdbc.getConnection(dbUrl, user, userPwd);


      var start = new Date();

      var stmt = conn.createStatement();

      // Read up to 1000 rows of data from the table and log them.

      // stmt.setMaxRows(1000);

      var results = stmt.executeQuery('SELECT * FROM hub_consulation_form');


      var sheet = SpreadsheetApp.getActiveSpreadsheet();

      var cell = sheet.getRange('A1');

      var numCols = results.getMetaData().getColumnCount();

      var row =0;


      while (results.next()) {

        var rowString = '';

        for (var col = 0; col < numCols; col++) {

          rowString += results.getString(col + 1) + '\t';

          cell.offset(row, col).setValue(results.getString(col +1 ));

        }

        row++

       Logger.log(rowString)

      }


      results.close();

      stmt.close();

      conn.close();


      var end = new Date();

      Logger.log('Time elapsed: %sms', end - start);

    }

    

Thursday, June 18, 2020

Update Images and content uysimh PHP mysqli

<?php
    include ('config.php');
$categoryid = $_REQUEST['Id'];
if(isset($_POST["user_submit"]))
{
    $name = $_REQUEST['name'];
   $email = $_REQUEST['email'];
   $phone = $_REQUEST['phone'];
   $visa_upload = $_REQUEST['visa_upload'];
   $visa_expiry = $_REQUEST['visa_expiry'];
   $license_upload = $_REQUEST['license_upload'];
   $licence_expiry = $_REQUEST['licence_expiry'];
   $passport_upload = $_REQUEST['passport_upload'];
   $passwport_expiry = $_REQUEST['passwport_expiry'];
 
    $rand = rand(0000,9999);
$filename = $_FILES['visa_upload']['name'];
$filetmpname = $_FILES['visa_upload']['tmp_name'];
$folder ='imagesuploadedf/';
move_uploaded_file($filetmpname, $folder.$filename);
  $timestamp = date("Y-m-d");
 


$filename1 =$_FILES['license_upload']['name'];
$filetmpname = $_FILES['license_upload']['tmp_name'];
$folder ='imagesuploadedf/';
move_uploaded_file($filetmpname, $folder.$filename1);


$filename2 = $_FILES['passport_upload']['name'];
$filetmpname = $_FILES['passport_upload']['tmp_name'];
$folder ='imagesuploadedf/';
move_uploaded_file($filetmpname, $folder.$filename2);

 $sql = "UPDATE driver_register SET name='$name',email='$email',phone='$phone',visa_expiry='$visa_expiry',licence_expiry='$licence_expiry',passwport_expiry='$passwport_expiry' WHERE Id = $categoryid";

  if ($conn->query($sql) === TRUE) {
   

 
   if($filename!='')
   {
      move_uploaded_file($filetmpname, $folder.$filename);
            $ww1 = mysqli_query($conn,"update driver_register set visa_upload='$filename' where Id ='$categoryid'");
   }
      if($filename1!='')
   {
      move_uploaded_file($filetmpname, $folder.$filename1);
            $ww2 = mysqli_query($conn,"update driver_register set license_upload='$filename1' where Id ='$categoryid'");
   }
      if($filename2!='')
   {
     move_uploaded_file($filetmpname, $folder.$filename2);
            $ww3 = mysqli_query($conn,"update driver_register set passport_upload='$filename2' where Id ='$categoryid'");
   }
   
   
    echo '<script>alert("Update Successfully.");window.location.assign("all_driver.php");</script>';
  }
  else{
      echo '<script>alert("please Update Again....");window.location.assign("all_driver.php?Id='.$categoryid.'");</script>';
  }
}


$query=mysqli_query($conn,"select * from driver_register where Id = '$categoryid' ") ;                   
  if(mysqli_num_rows($query)>0)
  {
   $res=mysqli_fetch_assoc($query);
   $name = $res['name'];
   $email = $res['email'];
   $phone = $res['phone'];
   $visa_upload = $res['visa_upload'];
   $visa_expiry = $res['visa_expiry'];
   $license_upload = $res['license_upload'];
   $licence_expiry = $res['licence_expiry'];
   $passport_upload = $res['passport_upload'];
   $passwport_expiry = $res['passwport_expiry'];
   
    $image= $res['image'];
  }
?>

Tuesday, January 21, 2020

CSV data attachment using PHP Mysqli

This summary is not available. Please click here to view the post.

Delete table data using ajax file php Mysqli

<span id="new_select2" style="color:green;text-align:center;font-weight:bold;"></span> // Show div

  onchange="fetch_select2(this.value);"  //Click Function

<script type="text/javascript">
function fetch_select2(val)
{
$.ajax({
type: 'post',
url: 'https://sasnagar.co.in/ezboxes//wp-content/themes/Divi/delete_calender_date.php?del_id=<?php $del_date_id= $row_pack["id"]; echo $del_date_id; ?>',
data: {
 get_option1:val
},
success: function (response) {
 document.getElementById("new_select2").innerHTML=response;
}
});
}
$('#new_select2').delay(5000).fadeOut('slow');
</script>

Thursday, January 9, 2020

Get database record using month and year PHP MYSQLI

<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
            <th colspan="2" class="tble_fb">Calender</th>
            <th colspan="1" class="tble_fb">Order #</th>
            <th colspan="1" class="tble_fb">Order Status</th>
            <th colspan="5" class="tble_fb">Contact Info</th>
            <th colspan="3" class="tble_fb">Item Info</th>
            <th colspan="3" class="tble_fb">Rent Period</th>
            <th colspan="4" class="tble_fb">Delivery Info</th>
            <th colspan="4" class="tble_fb">Pick Up Info</th>
            <th colspan="1" class="tble_fb">Order Notes</th>
        </tr>
<tr>                     
    <td class="heading_cls">Date</td>
    <td class="heading_cls">Day</td>
    <td class="heading_cls">Order #</td>
    <td class="heading_cls">New Order</td>
        <td class="heading_cls">First Name</td>
        <td class="heading_cls">Last Name</td>
        <td class="heading_cls">Email</td>
        <td class="heading_cls">Phone</td>
        <td class="heading_cls">Secondary Phone</td>
        <td class="heading_cls">Package</td>
        <td class="heading_cls">Package Boxes</td>
        <td class="heading_cls">Added Items</td>
        <td class="heading_cls">Rent Period</td>
        <td class="heading_cls">Rent Extra Week(s)</td>
        <td class="heading_cls">Delivery Date</td>
        <td class="heading_cls">Delivery Address</td>
        <td class="heading_cls">Delivery Apt</td>
        <td class="heading_cls">Stair/Elevator</td>
        <td class="heading_cls">Pick Up Date</td>
        <td class="heading_cls">Pick Up Address</td>
        <td class="heading_cls">Pick Up Apt</td>
        <td class="heading_cls">Stair/Elevator</td>
        <td class="heading_cls">Order Notes</td>
        </tr>
</thead> 
    <tbody>
<?php
$servername = "localhost";
$username = "xxxxx";
$password = "xxxx(*()";
$dbname = "xxxx";
date_default_timezone_set('Canada/Eastern');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

@$month_year=$_REQUEST['month_year'];
if(@$_POST['cal_dat_get']){
$startdate = date("m/d/Y", strtotime($month_year));

}else{
$startdate =  date("m/d/Y");
}
$exp = explode('/', $startdate);
$year = $exp[2];
$month = $exp[0];
$day_01 = '01';

   for($day_01='01';$day_01<='31';$day_01++){
   $tada_01 = $month.'/'.$day_01.'/'.$year;
   if(@$_POST['cal_dat_get']){  
$sql_package = "SELECT * from xxxx WHERE payment_status='succeeded' AND (order_status_type='New Order' OR order_status_type='Delivered') and order_date like '%$tada_01%' order by id desc";
   }else{
   $sql_package = "SELECT * from xxxxx WHERE payment_status='succeeded' AND (order_status_type='New Order' OR order_status_type='Delivered') and order_date like '%$tada_01%' order by id desc";
   }


$result = $conn->query($sql_package);

$val_price = 0;

if ($result->num_rows > 0) {
    while($row_pack = $result->fetch_assoc()) {
?>
<tr>                     
   
 
        <td class="heading_cls"><?php echo $row_pack["first_name"]; ?></td>
        <td class="heading_cls"><?php echo $row_pack["last_name"]; ?></td>
        <td class="heading_cls"><?php echo $row_pack["email_personal"]; ?></td>
        <td class="heading_cls"><?php echo $row_pack["phone_number1"]; ?></td>
        </tr>
 
<?php
    }
} else {
    ?>
<tr>                     
        <td class="heading_cls" style="border-right: none;"></td>
        <td class="heading_cls" style="border-right: none;"></td>
        <td class="heading_cls" style="border-right: none;"></td>
        <td class="heading_cls" style="border-right: none;"></td>
        <td class="heading_cls"></td>
        </tr>
<?php

}
  }
?> </tbody>
</table>

Get Weekly data using PHP MYSQLI

<table id="example" class="table table-striped table-bordered wely_tableset" style="width:100%">
<thead> 
<tr>
            <th style="line-height: 20px;border-right-color: #000;" colspan="2" class="tble_fb">For the week of Tuesday:</th>
            <th style="line-height: 50px;border-right-color: #000;" colspan="2" class="tble_fb"><?php date_default_timezone_set('Canada/Eastern'); $tuesday_date = date("m/d/Y", strtotime("previous tuesday"));
//echo $tuesday_date; echo '***';
$past_tuesday = date("d-M-Y", strtotime( "$tuesday_date -7 day" ) );
echo $past_tuesday; ?></th>
            <th colspan="2" style="border-right-color: #000;" class="tble_fb sdfrds">To Tuesday:
<span class="tblspn">Items Info</span>
</th>
            <th style="" colspan="3" class="tble_fb sdfrds"><?php  $tuesday_date = date("d-M-Y", strtotime("previous tuesday"));
echo $tuesday_date;
 ?>
<span class="tblspn">Payment Info</span>
</th>
        </tr>
<tr>                     
    <td class="heading_cls">Order Id</td>
        <td class="heading_cls">Order Status</td>
        <td class="heading_cls">Refer By</td>
    </tr>
</thead>
<tbody>
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx(*()";
$dbname = "xxxx";
date_default_timezone_set('Canada/Eastern');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
  $start_date_week = new DateTime('-7');
  $current_date_week = $start_date_week->format('m/d/Y');
  //echo $current_date_week;echo '****';
  $dt = date("m/d/Y");
  $day_date_future = date("m/d/Y", strtotime( "$dt -7 day" ) );
 //echo $day_date;die('hhhhhhhhhhh');

 $tuesday_date = date("m/d/Y", strtotime("previous tuesday"));
//echo $tuesday_date; echo '***';
$past_tuesday = date("m/d/Y", strtotime( "$tuesday_date -7 day" ) );
//echo $past_tuesday;
 
$sql_package = "SELECT * from xxxxx WHERE order_status_type='Completed' AND order_complete_date and ('$past_tuesday' AND '$tuesday_date') order by id";


$result = $conn->query($sql_package);

$val_price = 0;

if ($result->num_rows > 0) {
    while($row_pack = $result->fetch_assoc()) {
?>
<tr>                     
    <td class="heading_cls size_sett"><?php $order_id_pac = $row_pack["order_id"];echo $order_id_pac; ?></td>
        <td class="heading_cls" style="background:#c6e0b3;"><?php echo $row_pack["order_status_type"]; ?></td>
        <td class="heading_cls size_sett"><?php echo '$'.$row_pack["package_total"]; $val_price += $row_pack["package_total"];?></td>
    </tr>
<?php
    }
} else {
   // echo "0 results";
}
?>
 <tr>

<td style="border-left: none !important;border-right: none !important;font-size:0px;">Total</td>
<td style="font-weight:bold;">Total</td>
<td style="font-weight:bold">$<?php echo number_format($val_price); ?></td>
</tr>
</tbody>

</table>

Tuesday, November 5, 2019

Pasword update using php mysqli

 <?php
                       /*update profile */
                             include 'connection.php';
                           
                          $email_session = $_SESSION["name"];

if (count($_POST) > 0) {
    $result = mysqli_query($con, "SELECT * from register WHERE email = '".$email_session."' or phone_number = '".$email_session."'");
    $row = mysqli_fetch_array($result);
    if ($_POST["currentPassword"] == $row["password"]) {
        mysqli_query($con, "UPDATE register set password='" . $_POST["newPassword"] . "' WHERE email = '".$email_session."' or phone_number = '".$email_session."'");
        $message = "Password Changed";
    } else
        $message = "Current Password is not correct";
}
                           
                        ?>



 <form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div style="width:500px;">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
<tr class="tableheader">
<td colspan="2">Change Password</td>
</tr>
<tr>
<td width="40%"><label>Current Password</label></td>
<td width="60%"><input type="password" name="currentPassword" class="txtField"/><span id="currentPassword"  class="required"></span></td>
</tr>
<tr>
<td><label>New Password</label></td>
<td><input type="password" name="newPassword" class="txtField"/><span id="newPassword" class="required"></span></td>
</tr>
<td><label>Confirm Password</label></td>
<td><input type="password" name="confirmPassword" class="txtField"/><span id="confirmPassword" class="required"></span></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>

<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;

currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;

if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>

Friday, July 26, 2019

How to Mysqli handing Duplicate.

Tables or result sets sometimes contain duplicate records. Sometimes, it is allowed but sometimes it is required to stop duplicate records. Sometimes, it is required to identify duplicate records and remove them from the table. This chapter will describe how to prevent duplicate records occurring in a table and how to remove already existing duplicate records.

Preventing Duplicates from Occurring in a Table

You can use a PRIMARY KEY or UNIQUE Index on a table with appropriate fields to stop duplicate records. Let's take one example: The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.
CREATE TABLE person_tbl (
   first_name CHAR(20),
   last_name CHAR(20),
   sex CHAR(10)
);
To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it's also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values −
CREATE TABLE person_tbl (
   first_name CHAR(20) NOT NULL,
   last_name CHAR(20) NOT NULL,
   sex CHAR(10),
   PRIMARY KEY (last_name, first_name)
);
The presence of a unique index in a table normally causes an error to occur if you insert a record into the table that duplicates an existing record in the column or columns that define the index.
Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQLi inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQLi to discard it silently without generating an error.
Following example does not error out and same time it will not insert duplicate records.
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
   -> VALUES( 'Jay', 'Thomas');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
   -> VALUES( 'Jay', 'Thomas');
Query OK, 0 rows affected (0.00 sec)
Use REPLACE rather than INSERT. If the record is new, it's inserted just as with INSERT. If it's a duplicate, the new record replaces the old one −
mysql> REPLACE INTO person_tbl (last_name, first_name)
   -> VALUES( 'Ajay', 'Kumar');
Query OK, 1 row affected (0.00 sec)

mysql> REPLACE INTO person_tbl (last_name, first_name)
   -> VALUES( 'Ajay', 'Kumar');
Query OK, 2 rows affected (0.00 sec)
INSERT IGNORE and REPLACE should be chosen according to the duplicate-handling behavior you want to effect. INSERT IGNORE keeps the first of a set of duplicated records and discards the rest. REPLACE keeps the last of a set of duplicates and erase out any earlier ones.
Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.
CREATE TABLE person_tbl (
   first_name CHAR(20) NOT NULL,
   last_name CHAR(20) NOT NULL,
   sex CHAR(10)
   UNIQUE (last_name, first_name)
);

Counting and Identifying Duplicates

Following is the query to count duplicate records with first_name and last_name in a table.
mysql> SELECT COUNT(*) as repetitions, last_name, first_name
   -> FROM person_tbl
   -> GROUP BY last_name, first_name
   -> HAVING repetitions > 1;
This query will return a list of all the duplicate records in person_tbl table. In general, to identify sets of values that are duplicated, do the following −
  • Determine which columns contain the values that may be duplicated.
  • List those columns in the column selection list, along with COUNT(*).
  • List the columns in the GROUP BY clause as well.
  • Add a HAVING clause that eliminates unique values by requiring group counts to be greater than one.

Eliminating Duplicates from a Query Result:

You can use DISTINCT along with SELECT statement to find out unique records available in a table.
mysql> SELECT DISTINCT last_name, first_name
   -> FROM person_tbl
   -> ORDER BY last_name;
An alternative to DISTINCT is to add a GROUP BY clause that names the columns you're selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns −
mysql> SELECT last_name, first_name
   -> FROM person_tbl
   -> GROUP BY (last_name, first_name);

Removing Duplicates Using Table Replacement

If you have duplicate records in a table and you want to remove all the duplicate records from that table, then here is the procedure −
mysql> CREATE TABLE tmp SELECT last_name, first_name, sex
   -> FROM person_tbl;
   -> GROUP BY (last_name, first_name);
mysql> DROP TABLE person_tbl;
mysql> ALTER TABLE tmp RENAME TO person_tbl;
An easy way of removing duplicate records from a table is to add an INDEX or PRIMAY KEY to that table. Even if this table is already available, you can use this technique to remove duplicate records and you will be safe in future as well.
mysql> ALTER IGNORE TABLE person_tbl 
   -> ADD PRIMARY KEY (last_name, first_name);

What is Sequence in Mysqli?

A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them. This chapter describes how to use sequences in MySQLi.

Using AUTO_INCREMENT column

The simplest way in MySQLi to use Sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQLi to take care.

Example

Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it's auto incremented by MySQLi.
mysql>CREATE TABLE tutorials_auto(
   id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(30) NOT NULL,PRIMARY KEY(id));
Query OK, 0 rows affected (0.28 sec)

mysql>INSERT INTO tutorials_auto(id,name) VALUES(NULL,'sai'),(NULL,'ram');
Query OK, 2 rows affected (0.12 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM insect ORDER BY id;
+----+------+
| id | name |
+----+------+
|  1 | sai  |
|  2 | ram  |
+----+------+
2 rows in set (0.05 sec)

Obtain AUTO_INCREMENT Values

LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve auto incremented value of last record.

PERL Example

Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle:
$dbh->do ("INSERT INTO tutorials_auto (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysqli_insertid};

PHP Example

After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ) −
mysql_query ("INSERT INTO tutorials_auto (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysqli_insert_id ($conn_id);

Renumbering an Existing Sequence

There may be a case when you have deleted many records from a table and you want to resequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having joins with other table.
If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique −
mysql> ALTER TABLE tutorials_auto DROP id;
mysql> ALTER TABLE tutorials_auto
   -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
   -> ADD PRIMARY KEY (id);

Starting a Sequence at a Particular Value

By default, MySQLi will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQLi will start sequence from 100.
mysql> CREATE TABLE tutorials_auto
   -> (
   -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
   -> PRIMARY KEY (id),
   -> name VARCHAR(30) NOT NULL, 
   -> );
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE.
mysql> ALTER TABLE tutorials_auto AUTO_INCREMENT = 100;

Obtaining and Using MySQLi Metadata

There are three informations, which you would like to have from MySQLi.
  • Information about the result of queries − This includes number of records affected by any SELECT, UPDATE or DELETE statement.
  • Information about tables and databases − This includes information pertaining to the structure of tables and databases.
  • Information about the MySQLi server − This includes current status of database server, version number etc.
It's very easy to get all these information at mysqli prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all these information. Following section will show you how to obtain this information.

Obtaining the Number of Rows Affected by a Query

PERL Example

In DBI scripts, the affected-rows count is returned by do( ) or by execute( ), depending on how you execute the query −
# Method 1
# execute $query using do( )
my $count = $dbh->do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

# Method 2
# execute query using prepare( ) plus execute( )
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

PHP Example

In PHP, invoke the mysqli_affected_rows( ) function to find out how many rows a query changed −
$result_id = mysqli_query ($query, $conn_id);
# report 0 rows if the query failed
$count = ($result_id ? mysqli_affected_rows ($conn_id) : 0);
print ("$count rows were affected\n");

Listing Tables and Databases

This is very easy to list down all the databases and tables available with database server. Your result may be null if you don't have sufficient privilege.
Apart from the method I have mentioned below, you can use SHOW TABLES or SHOW DATABASES queries to get list of tables or databases either in PHP or in PERL.

PERL Example

# Get all the tables available in current database.
my @tables = $dbh->tables ( );
foreach $table (@tables ){
   print "Table Name $table\n";
}

PHP Example

<?php
   $servername = "localhost:3306";
   $username = "root";
   $password = "";
   $dbname = "TUTORIALS";
   $conn = new mysqli($servername, $username, $password, $dbname);
   
   if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   } 
   echo"Database connected";
   $sql="SHOW DATABASES";
   
   if (!($result = mysqli_query($conn,$sql))) {
      printf("Error: %s\n", mysqli_error($conn));
   }
   while( $row = mysqli_fetch_row( $result ) ){
      if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
         echo $row[0]."\r\n";
      }
   }
   $conn->close();
?>

Getting Server Metadata

There are following commands in MySQL which can be executed either at mysql prompt or using any script like PHP to get various important informations about database server.
Sr.No.Command & Description
1
SELECT VERSION( )
Server version string
2
SELECT DATABASE( )
Current database name (empty if none)
3
SELECT USER( )
Current username
4
SHOW STATUS
Server status indicators
5
SHOW VARIABLES
Server configuration variables

What is Clone Tables in Mysqli?

There may be a situation when you need an exact copy of a table and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values, and so forth.
You can handle this situation by following steps −
  • Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
  • Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have exact clone table.
  • Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.

Example

Try out the following example to create a clone table for tutorials_inf.

Step 1

Get complete structure about table.
mysql> SHOW CREATE TABLE tutorials_inf \G;
*************************** 1. row ***************************
       Table: tutorials_inf
Create Table: CREATE TABLE `tutorials_inf` (
   `id` int(11) NOT NULL,
   `name` varchar(20) NOT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `AUTHOR_INDEX` (`name`),
   UNIQUE KEY `NAME_INDEX` (`name`),
   KEY `id` (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1
1 row in set (0.05 sec)

ERROR: No query specified

Step 2

Rename this table and create another table.
mysql> CREATE TABLE tutorials_clone(
   -> id int(11) NOT NULL,
   -> name varchar(20) NOT NULL,
   -> PRIMARY KEY (id),
   > UNIQUE KEY AUTHOR_INDEX (name),
   -> UNIQUE KEY NAME_INDEX (name),
   ->  KEY id (id));
Query OK, 0 rows affected (1.80 sec)

Step 3

After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
mysql> INSERT INTO tutorials_clone(id,name) SELECT id,name from tutorials_inf;
Query OK, 4 rows affected (0.19 sec)
Records: 4  Duplicates: 0  Warnings: 0
Finally, you will have exact clone table as you wanted to have.

What is Temporary Tables in Mysqli?

The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates.
As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQLi client program, then the temporary table will exist until you close the client or manually destroy the table.

Example

Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysqli_query() function.
mysql> CREATE TEMPORARY TABLE SalesSummary (
   -> product_name VARCHAR(50) NOT NULL
   -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
   -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
   -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
   -> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO SalesSummary
   -> (product_name, total_sales, avg_unit_price, total_units_sold)
   -> VALUES
   -> ('cucumber', 100.25, 90, 2);

mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber     |      100.25 |          90.00 |                2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command, then your temporary table would not be listed out in the list. Now, if you will log out of the MySQLi session and then you will issue a SELECT command, then you will find no data available in the database. Even your temporary table would also not exist.

Dropping Temporary Tables

By default, all the temporary tables are deleted by MySQLi when your database connection gets terminated. Still if you want to delete them in between, then you do so by issuing DROP TABLE command.
Following is the example on dropping a temporary table −
mysql> DROP TABLE SalesSummary;
mysql>  SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist

What is Indexes in Mysqli?

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
While creating index, it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, indexes are also type of tables, which keep primary key or index field and a pointer to each record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to insert or update index values as well.

Simple and Unique Index

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table.
CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example, we can create an index on tutorials_inf using NAME_INDEX.
CREATE UNIQUE INDEX NAME_INDEX ON tutorials_inf(name);
You can create a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name.
mysql> CREATE UNIQUE INDEX NAME_INDEX ON tutorials_inf (name DESC);

ALTER command to add and drop INDEX

There are four types of statements for adding indexes to a table −
  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list) − This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
  • ALTER TABLE tbl_name ADD INDEX index_name (column_list)− This adds an ordinary index in which any value may appear more than once.
  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.
Here is the example to add index in an existing table.
mysql> ALTER TABLE tutorials_inf ADD INDEX (id);
You can drop any INDEX by using DROP clause along with ALTER command. Try out the following example to drop above-created index.
mysql> ALTER TABLE tutorials_inf DROP INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out the following example to drop above-created index.

ALTER Command to add and drop PRIMARY KEY

You can add primary key as well in the same way. But make sure Primary Key works on columns, which are NOT NULL.
Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.
mysql>  ALTER TABLE tutorials_inf MODIFY id INT NOT NULL;
mysql> ALTER TABLE tutorials_inf ADD PRIMARY KEY (id);
You can use ALTER command to drop a primary key as follows:
mysql> ALTER TABLE tutorials_inf DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.

Displaying INDEX Information

You can use SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound −
Try out the following example
mysql> SHOW INDEX FROM table_name\G
........