Exclude certain columns from SHOW COLUMNS mysql - php

I have this query: SHOW COLUMNS FROM mash which works fine in my while loop for building a select element made from table column names. But in my table i have "id" and "tstamp" which i dont want in the select element, is this possible to exclude these columns?
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";

PHP Way:
Use a continue in the while loop, when those fields are fetched, like this:
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
if($row[0] == 'id' || $row[0] == 'tstamp')
continue;
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";
This will just skip the id and tstamp fields and process all others. continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
MySQL Way:
Remove those fields in the query like this:
SHOW COLUMNS FROM mash WHERE Field NOT IN ('id', 'tstamp');

Yes, it's possible. Instead of using SHOW COLUMNS use INFORMATION_SCHEMA.
INFORMATION_SCHEMA is the ANSI way of extracting metadata from a relational database. In MySQL you can use:
$sql = "select column_name from information_schema.columns c " +
" where c.table_schema = 'db_name' " +
" and c.table_name='table_name' " +
" and c.column_name like 'name%'";
Information Schema has the advantage that is SQLANSI compliant. You can use it in MySQL, PostgreSQL, SQLServer and other relational databases.

You can use LIKE operator.
SHOW COLUMNS FROM mash LIKE "name%"

To see just the "Collation" column that shows up in SHOW FULL COLUMNS from tablename for just one field, it's:
select COLLATION_NAME from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';
Ddrop the fieldname in the where, if you want to see that column for all field names.
To see all possible column names that show up from SHOW FULL COLUMNS so that you can select what you want:
select * from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

List all tables within DB

I am trying to show a list of all tables within my database
I have the below code:
$result=mysql_query("SELECT TABLE_NAME FROM vogaldes_fuse.INFORMATION_SCHEMA.Tables ")or die('ERROR 315' );
$num_rows = mysql_num_rows($result);
echo "$num_rows";
However this does not show any results, instead i see ERROR 315
Also, I want to list the table names, how do I get these?
UPDATE
I have managed to get the correct number of tables using the below:
$result=mysql_query("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse';")or die('ERROR 315' );
The last bit of my question still stand, how do I turn each table name into a string that I can then use to list in a select dropdown?
Just use select TABLE_NAME from information_schema.tables Remove vogaldes_fuse. database name
To create dropdown of table use
$result = mysql_query("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse'") or die('ERROR 315');
if (mysql_num_rows($result) > 0) {
echo "<select name='table_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['TABLE_NAME'] . "'>" . $row['TABLE_NAME'] . "</option>";
}
echo "</select>";
}
UPDATED
For select TABLE_SCHEMA except some table
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse' AND TABLE_NAME NOT
IN (
'hr_employees', 'hr_roles'
)
Run This
USE 'your db name';
SHOW TABLES;
SELECT FOUND_ROWS();
Use This
$sql = "SHOW TABLES FROM 'your db name'";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}</br>";
}
mysql_free_result($result);
Hope this help .
For MySQL:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='dbName'

MySQL - Get column names from table and display them (using PHP)

I want to take the column names from a table and display them, so i can compare them later.
To get the names, i tried:
$entry = mysqli_query($con, 'SHOW COLUMNS FROM table');
and
$entry = mysqli_query($con, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = 'table'");
I don't know whether this runs correctly or not, since i don't get an error message there.
If i try to print the contents of $entry via echo, i keep getting errors.
Previously in my code, i print other entries using:
$test = mysqli_query($con, 'SELECT DISTINCT LK_Release FROM table');
while($row = mysqli_fetch_object($test))
{
echo "Releasename: " . "$row->LK_Release". "<br>";
... }
This output works for me.
What i tried to output the columnnames:
while($row = mysqli_fetch_object($entry))
{
echo $row;
}
Any ideas?
Your query is already correct. But you lack something in the fetching:
while($row = mysqli_fetch_object($entry))
{
echo $row->Field . '<br/>';
// ^ access the objects properties
}
The following SQL statements are nearly equivalent:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
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;

How to insert into a table after doing a select in a form

I have a PHP form that is collecting information and writing it to a database and it is working correctly. I have one field that is a select to choose entries from an existing table. I would like that result to be inserted into a different table but can't get the insert into to work. I would like to insert the FacilityName field chosen in the select to table2.
$result = mysql_query("SELECT * FROM facility");
print "<select name=\"Id\" > \n";
while ($row = mysql_fetch_array($result)){
$Id = $row['Id'];
$FacilityName = $row['FacilityName'];
print "<option value=$Id>$FacilityName\n";

mysql query written using php

$u_id=$event_assoc['Uniqueid'];
echo $u_id."\n";
$result1 = mysql_query("SELECT * FROM eventdetail WHERE unique_id = '$u_id'", $con1);
while($row = mysql_fetch_array($result1))
{
echo 'in eventdetail'."\n";
$e_id= $row['event_id'];
$destination= $row['destination'];
$uniqueid= $row['unique_id'];
$call_num= $row['channelid'];
}
echo mysql_num_rows($result1);
echo $e_id."\n";
echo $destination."\n";
echo $call_num."\n";
echo $uniqueid."\n";
if(mysql_num_rows($result1)>0)
{
echo 'calculate'."\n";
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
$bil = mysql_fetch_array($result);
$bill= (float) $bil['sum(billsec)'];
echo $bill."\n";
this is my code..
whenever i try to execute sum function query it retruns top row's billsec instead of addition of all row's billsec
You are doing a where on an unique ID in the sum query. Remove the where and it'll work
You are using unique id in your query.. And in a table single row will have that id, thats why you are getting top row's billsec... Remove the where clause in second query, and then check.
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
i guess there is a bug in this area...look again
The PHP statement for the SQL SUM Query should be:-
$result= mysql_query("SELECT sum(`billsec`), `uniqueid` FROM `cdr` GROUP BY `uniqueid` HAVING `uniqueid` = '$uniqueid'", $con2);
You need to use the clause "GROUP BY" whenever you are using any MySQL Aggregate functions (if needed). Also if you are using any aggregate functions (like "SUM", "MAX" etc), then you cannot use "WHERE" clause on the field (in this case, the field is "uniqueid") which is being used in the "GROUP BY" clause.
Hope it helps.

Categories