Table creation in PHP

Table creation in PHP

To create a table in PHP, you can use the following steps:

  1. Establish a database connection using PHP’s mysqli or PDO extension.
  2. Define a SQL query that creates a table. For example, the following code creates a table called “users” with three columns:
CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  password VARCHAR(255) NOT NULL
);

Execute the SQL query using the mysqli_query() or PDO::exec() function, depending on which extension you are using. Here is an example using the mysqli extension:

$conn = mysqli_connect("localhost", "username", "password", "database_name");
$sql = "CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully.";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

Note that you should always sanitize user input and use prepared statements to prevent SQL injection attacks.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Share this post
[social_warfare]
Passing a Parameter on a query string
Security Market and Emerging Trends

Get industry recognized certification – Contact us

keyboard_arrow_up