I want to get the sum total of the table columns in my database.
I've tried using the following code but have not been successful.
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM User_Table');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
Thank you very much!!
I hope you try to find total number of record of a table of User_Table
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM User_Table');
//or like the query for return last row that indicate total number of record
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;');
$row = mysqli_fetch_assoc($result);
$sum = $row['id'];
echo $sum;
// or using count
$result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;');
$row = mysqli_fetch_assoc($result);
$sum = $row['total_row '];
echo $sum;
As of my understanding you need count the number of columns your database have. If I am not wrong, you may please use the query below
select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position
Hope this helps. Thanks
I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco
How can I select data in the same query from two different databases into the same server?
This is what I'm doing, but my query doesn't works:
$sqlquery = "SELECT * FROM database_2.table_2 WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2";
$result = mysql_query($sqlquery);
$number = mysql_numrows($result);
$i = 0;
if ($number < 1) {
print "DOH";
}else{
while ($number > $i) {
$content = mysql_result($result,$i,"database_2.table_2.data_3");
print "$content";
$i++;
}
}
The problem is not about different databases.
Your WHERE clause references the field database_1.table_1.data_1 which was not supplied in the FROM clause.
Didn't you mean something like
SELECT *
FROM database_2.table_2
JOIN database_1.table_1
ON (database_2.table_2.some_field = database_1.table_1.some_other_field)
WHERE database_1.table_1.data_1 LIKE database_2.table_2.data_2
?
Also,
echo mysql_error();
after your failed query - this will give you a clue about what's wrong.
isn't numrows underscored?
$number = mysql_num_rows($result);
http://php.net/manual/en/function.mysql-num-rows.php
try this
SELECT * FROM database_2.table_2 t2 INNER JOIN database_1.table_1 t1
ON t1.data_1 = t2.data_2
I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !
So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");
Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x
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)