PHP/MySQL Database/Table Create

Материал из Web эксперт
Перейти к: навигация, поиск

Create new table in MySQL

<?php
$linkID = mysql_connect("mysql153.secureserver.net", "wbex", "password");
mysql_create_db("new_db", $linkID);
mysql_select_db("new_db");
$query = "CREATE TABLE new_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, new_col VARCHAR(25))";
$result = mysql_query($query);
$axe = mysql_drop_db("new_db");
?>



Create table and install data

 <?
  define("DBName","test");
  define("HostName","localhost");
  define("UserName","root");
  define("Password","");
  
  if(!mysql_connect(HostName,UserName,Password)){ 
    echo "Cannot get connected to the database ".DBName."!<br>";
    echo mysql_error();
    exit;
  }
  mysql_select_db(DBName);
  // Creating the t table. If it already exists,
  // "@" overrides the error message
  @mysql_query("create table t(id int, a double)");
  // Inserting 10 records into the table
  for($i=0; $i<10; $i++){ 
    $id=time();
    mysql_query("insert into t(id, a) values($id, "$i")");
  }
  
  // Outputting all records
  $r=mysql_query("select * from t");
  
  for($i=0; $i<mysql_num_rows($r); $i++) { 
    $f=mysql_fetch_array($r);
    echo "$f[id] -> $f[a]<br>\n";
  }
?>



Creating a Table in MySQL

 <?php
  $host="mysql153.secureserver.net";
  $uname="wbex";
  $pass="password";
  $database="wbex";
  $tablename="mytable";
  $connection= mysql_connect ($host, $uname, $pass) or die ("Database connection failed!");
  $result=mysql_select_db ($database) or die ("Database could not be selected");
  $query = "create table ". $tablename ." (name varchar (20) Not Null, email varchar (40) Not Null)";
  $result = mysql_query ($query);
  
  if (! $result) {
    die ("Query could not be executed.");
  } else {
    echo $tablename." created in the megabase database.\n";
  }
  ?>



Table-Creation Script

<?
$db_name = "wbex";
$connection = @mysql_connect("mysql153.secureserver.net", "wbex", "password") or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());
$columnNames = array("col1","col2","col3");
$columnTypes = array("int","Date","double");
$sql = "CREATE TABLE MyTable (";
for ($i = 0; $i < count($columnNames); $i++) {
     $sql .= $columnNames[$i]." ".$columnTypes[$i]. ", ";
}
$sql = substr($sql, 0, -2);
$sql .= ")";
echo($sql);
$result = mysql_query($sql,$connection) or die(mysql_error());
if ($result) {
     $msg = "<P>MyTable has been created!</P>";
     
     echo($msg);
}
?>