I want to check a MySQL table in php to see if a column with a specific name exists in that table.
For example, a table might contain columns like "col1-abc", "col2-abc" and col2-xyz" but NOT "col1-xyz".
What is php code that will do this?
Thank you
ASKER
$pdo = new PDO( //connect to your DB here );
$sqlStr = <<<EOT
SELECT COUNT(1)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA='xyz' AND
TABLE_NAME='yourTable' AND
COLUMN_NAME='col1-xyz'
EOT;
$result = $pdo->query($sqlStr);
$columnExists = (bool)$result->fetchColumn();
Let's break that down. We're making a connection your DB using PDO. We're then running a query against the COLUMNS table (this contains all the info about all the columns in all the tables across all the databases) which will count the number of records that match the criteria - it checks for a named Column (COLUMN_NAME), within a named Table (TABLE_NAME), within a named Database (TABLE_SCHEMA).ASKER
ASKER
$someVariable = new PDO('mysql:host=localhost;dbname=lakoshva_dev;charset=utf8mb4', $user, $pass);
Once you've got the connection stored in a variable,, then you use that to execute commands against your DB ($pdo->query() etc.)// Procedural
$myDb = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// Object (OOP)
$conn = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
If you are using MySQLi, then you'll need to adapt my code above as it was written specifically for PDO - a much better library in my opinion
ASKER
ASKER
ASKER
<?php
requite_once "db_connect_nb.php";
Now your code will either fail on the require ( the file can't be found) or it will fail on the connection - in which case you need to check that code specifically. Either way, you'll know exactly where you code fails.
ASKER
ASKER
ASKER
ASKER
ASKER
ASKER
PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.
TRUSTED BY
Open in new window