I created mysql tables and there I have put some columns.
Now I want to check that a certain column exists in the database via php.
Like this:
try
$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;
if($exists) {
// do your stuff
}
For more :- MySQL, Check if a column exists in a table with SQL
Note:- mysql_* is deprecated use mysqli
or PDO
Suppose you want to find the customer who has placed at least one sales order, you can use the EXISTS operator as follows:
SELECT customerNumber,
customerName
FROM customers
WHERE EXISTS
(SELECT 1
FROM orders
WHERE orders.customernumber = customers.customernumber);
For each row in the customers table, the query checks the customerNumber in the orders table.
If the customerNumber, which appears in the customers table, exists in the orders table, the subquery returns the first matching row. As the result, the EXISTS operator returns true and stops scanning the orders table. Otherwise, the subquery returns no row and the EXISTS operator returns false.
To get the customer who has not placed any sales orders, you use the NOT EXISTS operator as the following statement:
SELECT customerNumber,
customerName
FROM customers
WHERE NOT EXISTS
(SELECT 1
FROM orders
WHERE orders.customernumber = customers.customernumber);
This is simple but it works for me:
1) Select all from the table you want.
$qry = "SELECT * FROM table";
2) Bring the result and verify if the field exists.
if( $result = $mysqli->query($qry) && isset($result['field_you_want']) ){
//Exists
}else{
//Doesn't exists
}
Ok I spent 5 hours on this issue looking through every (sometimes ridiculously convoluted) StackOverflow answer, never finding a working answer, and the answer is so frustratingly simple you will kick yourself (as did I):
php 7
$mysqli = new mysqli($mysql_url, $mysql_user, $mysql_password, $db_name);
$column_name = "my_column";
$table_name = "my_table";
if ($mysqli->query("SELECT $column_name FROM $table_name")){
//my_column exists in my_table
}
else{
//my_column doesn't exist in my_table
}
Databases 101....
You can use mysql_list_fields and mysql_num_fields to get columns of a table
$fields = mysql_list_fields('database_name', 'table_name');
$columns = mysql_num_fields($fields);
In PHP:
$fields = mysql_list_fields('database_name', 'table_name');
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if (!in_array('price', $field_array))
{
$result = mysql_query('ALTER TABLE table_name ADD price VARCHAR(10)');
}
This should also help you:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
ALTER TABLE TEST ADD TEST_DATE DATETIME
END
Or you can do:
Show columns from table like 'string';
Check out this question : How can I check if mysql table column even exists?