...

View Full Version : Creating/Populating MSQL table with PHP



rosiedee
01-25-2012, 04:21 PM
Hello,
What is the code to populate a MSQL table with php?
I have the code to access the database and to create the table, but how to I manually put in the data?


<?php

$con = mysql_connect("localhost","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";

// Execute query
mysql_query($sql,$con);

mysql_close($con);

?>

Fou-Lu
01-25-2012, 04:38 PM
Not sure I really understand your question. SQL and PHP are completely different languages, just that PHP has the ability to connect with SQL. You'll need to learn SQL in order to create the INSERT required to write table data. The command in PHP is the same: mysql_query, its the SQL command that changes.

rosiedee
01-25-2012, 05:39 PM
Hello, nevermind. Thank you for your response, but I found the second part of the tutorial. Once a database is created, the code to populate it would be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>

Fou-Lu
01-25-2012, 05:50 PM
Yep, except you shouldn't really wrap the 'age' into quotations. In strict mode this will fail since the integer datatype will not match that of the string. In loose mode, this is an implicit conversion, but will sacrifice a cycle to convert. Not a big deal with two insertions, but on say 500K insertions you will likely bring an insertion up from say 15 minutes to more like 4 hours.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum