0

I have a script that reads my database table fields. Its not reading the first column which is the id.It reads the other fields and adds them into the array. I have added in the for loop a -1 to get every field but to no success.

$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);

$key_values = array();

$link = mysql_connect($host,$user,$pass);
$db_select = mysql_select_db($dbselect);
$query = mysql_query('SHOW COLUMNS FROM '.$table.'');


if (!$link) {
    die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = $dbselect;
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from '.$table.'', $link);
$num_fields = mysql_num_fields($res);
for($i=0;$i<$num_fields;$i++){

$key_values[]=mysql_field_name($res,$i);

}
echo "<pre>";
print_r($key_values);
echo "</pre>";
David Jashi
  • 4,490
  • 1
  • 21
  • 26
saiyan101
  • 610
  • 4
  • 12
  • 28

3 Answers3

0

I don't see why it might be doing that, but this should be more reliable:

$query = mysql_query('select * from `%s`', mysql_real_escape_string($table), $link);
while ($result = mysql_fetch_array($query)) {
  print_r(array_keys($result));
}
kuujo
  • 7,785
  • 1
  • 26
  • 21
0

Try to use php native function mysql_fetch_array (also you need view this quastion before) After try this code ($res === 'resources'):

$res = mysql_query('select * from '.$table.'', $link);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
    $key_values[] = array_keys($row);
}
echo "<pre>";
print_r($key_values);
echo "</pre>";
Community
  • 1
  • 1
RDK
  • 4,540
  • 2
  • 20
  • 29
0

There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.

<?php
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);

$db = new mysqli($host,$user,$pass,$dbselect);
if($db->connect_error)
        die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

// NOTE real_escape_string may not work for tables untested
$result = $db->query("SELECT * FROM " . $db->real_escape_string($table));
if (!$result)
        die "Error: " . $db->error;

while ($row = $result->fetch_object())
{
    echo $row->id;
}
$result->close();
$db->close();
Prix
  • 19,417
  • 15
  • 73
  • 132