How can I check if mysql table column even exists? - php

How can I check if mysql table field even exists ?
The column name is 'price' and I need to see if it exists.
Haven't understood really how the 'EXISTS' works...
Any examples or ideas ?
Thanks

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';
There has been a similar question posed on SO here before.

Try:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME = 'Price')
BEGIN
-- do something, e.g.
-- ALTER TABLE TEST ADD PRICE DECIMAL
END

Another way of doing it in PHP:
$chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1");
$mycol = mysql_fetch_array($chkcol);
if(isset($mycol['price']))
echo "Column price exists! Do something...";

Well, one way is to do:
select price from your_table limit 1
If you get an error:
#1054 - Unknown column 'price' in 'field list'
then it does not exists.

I found this very useful. It will list all the tables that has that column name.
SELECT table_name,
column_name
FROM information_schema.columns
WHERE column_name LIKE '%the_column_name%'

well here is a function to check out if a particular column exists or not.
public function detect_column($my_db, $table, $column)
{
$db = mysql_select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'"; //query
$result = mysql_query($sql); //querying
if(mysql_num_rows($result) == 0) //checks the absence of column
echo "column $column doesn't exist !";
// write your code here!
else
echo "column $column exists!";
}
well if you are designing a frame work, then this function may come to your aid. This function checks for the presence of column when $flag is set to '1' and absence of column when $flag is set to '0'.
public function detect_column($my_db, $table, $column, $flag)
{
$this->select_db($my_db); //select the database
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == $flag)
return true;
else
return false;
}

You could get a description of all the column in your table.
desc your_table;

I just done something like this using this function for Wordpress, this for update tables that having new chnages on it
public function alterTable() {
$table_name = $this->prefix . $this->tables['name'];
$select = "select * from `{$table_name}` where 0=0 limit 1;";
$query = $this->db->get_results($select, ARRAY_A);
if (isset($query[0]) && !key_exists('adv', $query[0])) {
$sql = "ALTER TABLE `{$table_name}` ADD `me` INT NULL DEFAULT NULL ;";
$this->db->query($sql);
}
}

Related

Make an array from a select with multiple rows

I'm trying my best here to find a solution for my issue, but with no luck.
I have a SELECT in my PHP to retrieve some products information like their IDs.
mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
Every time I run this SELECT, I get 5 rows as result. After that I need to run a DELETE to kill those 5 rows using their id_item in my WHERE condition. When I run, manually, something like:
DELETE FROM mytable WHERE id_item IN (1,2,3,4,5);
It works! But my issue is that I don't know how to make an array in PHP to return (1,2,3,4,5) as this kind of array from my SELECT up there, because those 2 other conditions may vary and I have more "status = 0" in my db that can't be killed together. How am I suppose to do so? Please, I appreciate any help.
Unless there is more going on than what is shown, you should never have to select just to determine what to delete. Just form the DELETE query WHERE condition as you would in the SELECT:
DELETE FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'
But to answer how to get the IDs:
$result = mysqli_query($link, "SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
while($row = mysqli_fetch_assoc($result)) {
$ids[] = $row['id_item'];
}
$ids = implode(',', $ids);
Move to PDO or MySQLi now.
First of all you shouldn't be using mysql_query anymore as the function is deprecated - see php.net
If this is a legacy application and you MUST use mysql_query you'll need to loop through the resource that's returned by mysql_query, which should look something like this
$result = mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$idArray = array();
while ($row = mysql_fetch_assoc($result)) {
$idArray[] = $row['id_item'];
}
if(count($idArray) > 0) {
mysql_query("DELETE FROM mytable WHERE id_item IN (" . implode(',' $idArray) . ")");
}
As said before, probably you don't even need a select. But you can do a select, grouping all ids together, and then put it in the delete IN.
$result = mysql_query("SELECT GROUP_CONCAT(DISTINCT id_item) AS ids FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$ids = mysql_result( $result , 0, 'ids') ; // 1,2,3,4,5
if ($ids != ""){
mysql_query("DELETE FROM mytable WHERE id_item IN (" . $ids . ")");
}
GROUP_CONCAT

Return information schema column comments into a php array

The follwing shows how to output an individual table column comment.
$db = mysql_connect("localhost","root","xyz") or die(mysql_error());
mysql_select_db("database",$db) or die(mysql_error());
function table_description($t,$c,$d){
$sql = "SELECT column_comment FROM information_schema.columns
WHERE table_name = '$t' AND column_name LIKE '$c'";
$query = mysql_query($sql,$d) or die(mysql_error());
$v = mysql_fetch_row($query);
if($v){
return $v[0];
}
return 'Table description not found';
}
echo table_description('table','col',$db);
However I would like table_description to return an array of every column comment in that table.
e.g. Column_Name, Column_Comments (so "RecID" => "ID of the record") etc.
I have little experience of working with php arrays/ converting resultsets to array.
loop through the query results with a while loop, store the results in an array outside of the scope of the while loop...
for example:
function table_description($t,$c,$d){
$t = mysql_real_escape_string($t); //prevent sql injection
$c = mysql_real_escape_string($c);
$sql = "SELECT column_comment,column_name FROM information_schema.columns
WHERE table_name = '$t' AND column_name LIKE '$c'";
$query = mysql_query($sql,$d) or die(mysql_error());
$columnArray = array();
while($result = mysql_fetch_array($query)){
$columnArray[] = array('column_comment' => $result['column_comment'], 'column_name' => $result['column_name']);
}
return $columnArray;
}
$columnArray[0]['column_name'] would return the column name of the first element of the array $columnArray

Mysql Syntax Error... or is it the PHP?

Can someone help me figure out what is wrong with this function??
I am getting a mysql syntax error...
function category_exists($name) {
$name = mysql_real_escape_string($name);
$query = mysql_query("SELECT COUNT(1) FROM 'categories' WHERE 'name' = '{$name}'");
return (mysql_result($query, 0) == '0')? false : true;
}
You should not have quotes around your table and column name (categories, name). If you need to escape a table or column names, you should use backquotes (`). IE:
$query = mysql_query("SELECT COUNT(1) FROM `categories` WHERE `name` = '{$name}'");
function category_exists($name) {
$name = mysql_real_escape_string($name);
$query = mysql_query("SELECT COUNT(1) FROM `categories` WHERE `name` = '{$name}'");
return (mysql_result($query, 0) == '0')? false : true;
}
You need either backquotes (`) or NO quotes around table names and field names.
Strings are quoted. Object names (tables, columns...) are not.
Try changing the query to
"SELECT COUNT(*) FROM 'categories' WHERE name = '$name'"

Checking for empty fields in mysql table

I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...

Get table column names in MySQL?

Is there a way to grab the columns name of a table in MySQL using PHP?
You can use DESCRIBE:
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
Or you can use SHOW COLUMNS:
SHOW COLUMNS FROM my_table;
Or to get column names with comma in a line:
SELECT group_concat(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
[AND table_schema = 'db_name']
[AND column_name LIKE 'wild']
SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']
Reference: INFORMATION_SCHEMA COLUMNS
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
There's also this if you prefer:
mysql_query('SHOW COLUMNS FROM tableName');
This solution is from command line mysql
mysql>USE information_schema;
In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement
mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->';
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name
although EXPLAIN is more commonly used to obtain information about the query execution plan.
How about this:
SELECT #cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
SET #cCommand = CONCAT( 'SELECT ', #cCommand, ' from my_database.my_table;');
PREPARE xCommand from #cCommand;
EXECUTE xCommand;
Look into:
mysql_query('DESCRIBE '.$table);
The MySQL function
describe table
should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)
The mysql_list_fields function might interest you ; but, as the manual states :
This function is deprecated. It is
preferable to use mysql_query() to
issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
You may also want to check out mysql_fetch_array(), as in:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}
in mysql to get columns details and table structure by following keywords or queries
1.DESC table_name
2.DESCRIBE table_name
3.SHOW COLUMNS FROM table_name
4.SHOW create table table_name;
5.EXPLAIN table_name
you can get the entire table structure using following simple command.
DESC TableName
or you can use following query.
SHOW COLUMNS FROM TableName
$col = $db->query("SHOW COLUMNS FROM category");
while ($fildss = $col->fetch_array())
{
$filds[] = '"{'.$fildss['Field'].'}"';
$values[] = '$rows->'.$fildss['Field'].'';
}
if($type == 'value')
{
return $values = implode(',', $values);
}
else {
return $filds = implode(',', $filds);
}
this worked for me..
$sql = "desc MyTableName";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>";
}
I have write a simple php script to fetch table columns through PHP:
Show_table_columns.php
<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
$link = mysql_select_db($db) or die("no database") . mysql_error();
$count = 0;
if ($link) {
$sql = "
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$db'
AND table_name = 'table_name'"; // Change the table_name your own table name
$result = mysql_query($sql, $con);
if (mysql_query($sql, $con)) {
echo $sql . "<br> <br>";
while ($row = mysql_fetch_row($result)) {
echo "COLUMN " . ++$count . ": {$row[0]}<br>";
$table_name = $row[0];
}
echo "<br>Total No. of COLUMNS: " . $count;
} else {
echo "Error in query.";
}
} else {
echo "Database not found.";
}
} else {
echo "Connection Failed.";
}
?>
Enjoy!
mysqli fetch_field() worked for me:
if ($result = $mysqli -> query($sql)) {
// Get field information for all fields
while ($fieldinfo = $result -> fetch_field()) {
printf("Name: %s\n", $fieldinfo -> name);
printf("Table: %s\n", $fieldinfo -> table);
printf("Max. Len: %d\n", $fieldinfo -> max_length);
}
$result -> free_result();
}
Source: https://www.w3schools.com/pHP/func_mysqli_fetch_field.asp
The easy way, if loading results using assoc is to do this:
$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);
This you load a single result using this query, you get an array with the table column names as keys and null as value.
E.g.
Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)
after which you can easily get the table column names using the php function array_keys($result)

Categories