Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Working with MySQL Database

By: FYICenter.com

Part:   1  2  3   4  5  6  7 

(Continued from previous part...)

How To Create a Table?

If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:

<?php
  include "mysql_connection.php";

  $sql = "CREATE TABLE fyi_links ("
      . " id INTEGER NOT NULL" 
      . ", url VARCHAR(80) NOT NULL"
      . ", notes VARCHAR(1024)"
      . ", counts INTEGER"
      . ", time TIMESTAMP DEFAULT sysdate()"
      . ")";
  if (mysql_query($sql, $con)) {
    print("Table fyi_links created.\n");
  } else {
    print("Table creation failed.\n");
  }

  mysql_close($con); 
?>

Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:

Table fyi_links created.

How To Get the Number of Rows Selected or Affected by a SQL Statement?

There are two functions you can use the get the number of rows selected or affected by a SQL statement:

  • mysql_num_rows($rs) - Returns the number of rows selected in a result set object returned from SELECT statement.
  • mysql_affected_rows() - Returns the number of rows affected by the last INSERT, UPDATE or DELETE statement.

How To Insert Data into a Table?

If you want to insert a row of data into a table, you can use the INSERT INTO statement as shown in the following sample script:

<?php
  include "mysql_connection.php";

  $sql = "INSERT INTO fyi_links (id, url) VALUES ("
      . " 101, 'dev.fyicenter.com')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  $sql = "INSERT INTO fyi_links (id, url) VALUES ("
      . " 102, 'dba.fyicenter.com')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }

  mysql_close($con); 
?>

Remember that mysql_query() returns integer/FALSE on INSERT statements. If you run this script, you will get something like this:

1 rows inserted.
1 rows inserted.

How To Insert Rows Based on SELECT Statements?

If want to insert rows into a table based on data rows from other tables, you can use a sub-query inside the INSERT statement as shown in the following script example:

<?php
  include "mysql_connection.php";

  $sql = "INSERT INTO fyi_links"
      . " SELECT id+1000, url, notes, counts, time FROM fyi_links";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }

  mysql_close($con); 
?>

If you run this script, you will get something like this:

2 rows inserted.

(Continued on next part...)

Part:   1  2  3   4  5  6  7 


Selected Developer Jobs:

More...