简体   繁体   中英

Choose all columns from the table with types int and varchar

I have a table stored at the testdb (database) and I need to choose all the columns of int and varchar types from it. I know about function mysql_field_type but it doesn't work in the 5th version of php.

<?php
header('Content-Type: text/html; charset=utf-8');

$host = '127.0.0.1';
$user = 'root';
$pass = '';

$link = mysqli_connect($host , $user, $passw , 'testdb');

if(!$link){
    echo "Connection failure";
}else{
    echo "Connection success!";
}

$result = mysqli_query($link, 'SELECT * FROM `test_table`');

 while ($row = $result->fetch_assoc()) { 
    $table[] = $row; 
}
print_r ($table);

?>

Try running a query of the form:

select column_name
from Information_schema.columns
where table_name = 'test_table' and (data_type = 'int' or data_type = 'varchar');

This should return you a list of all columns in test_table that are of int or varchar. You can then iterate over them, and pull out the values for them either by query concatenation in PHP, or on a foreach.

You can use fetch_field for this. ( http://tr1.php.net/manual/tr/mysqli-result.fetch-field.php )

$cols = array();

while($field = $result->fetch_field()){
    if($field->type == 3 || $field->type == 253){
        $cols[] = $field->name;
    }
}
print_r($cols);

Since you are already storing your value in $table array try this on any column

if you want to select column name then your query should be like this

select column_name from Table_name

Use is_numeric function

foreach ($table as $new_array)
{
    if(is_numeric($new_array))
    {
        $number[]=$new_array;
    }
    else{
        $string[]=$new_array;
    }
}

print_r($string);//see the result
print_r($number);//see the result

Check this link:- http://php.net/manual/en/function.is-numeric.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM