For example: I have a table name tbl_admin and I have so many table elements within that table.
Like (id, fname, lname, contact_info, email, ip, date, status, etc.and so on upto 20 elements).
Now I need to exclude only 3 elements from that table as you can say (fname, lname and contact_info) and select all others. Is this possible by using the mysql query?
Please help me if this is possible. Thanks,
Short Answer
You can't exclude columns explicitly, but you can do so implicitly by selecting only the other columns:
SELECT
ID,
EMAIL,
IP,
DATE,
STATUS
FROM tbl_admin
Long Answer
It turns out I was wrong with the short answer, technically there is a way as illustrated with the question here.
To do this in PHP, I'd recommend creating a view in the MySQL database that would encapsulate the SQL. Then you would just select * from that view.
Alternatively, you could create a stored procedure, and pass in the names of the columns that you want to be filtered out.
Try:
$result = mysql_query("SHOW COLUMNS FROM tbl_admin");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$columns[] = $row['Field'];
}
}
//fill all columns here that you want to exclude
$columns_to_exclude = array('fname','lname','contact_info');
$sql = "SELECT (";
foreach($columns as $ind=>$val){
if(!in_array($val,$columns_to_exclude))
{
$sql .= $val.", ";
}
}
$sql = rtrim($sql,", ");
$sql .= ") FROM tbl_admin;";
echo $sql;
Select fname,sname,contact from table_admin
Yes, so you will have something like this:
SELECT
id,
fname,
lanem
FROM
tbl_admin
You just need to specify what are those and in what order. Instead of using the * to fetch all records (columns) in its default order.
Edit
SET #sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
Actually, I just got it from another's posts so all credits goes to him. HERE
Latest Answer
ANSWER BY Mahomedalid in Select all columns except one in MySQL?
SET #sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
For your situation replace the <columns_to_omit> with fname,lname,contact_info
Old Answer
Syntax for retrieving particular column values from table is
SELECT column_name(s)
FROM table_name
All columns can be retrieved using SELECT * instead of SELECT column_name(s)
if you are directing your question towards a particular language like PHP then the syntax can be like this
<?php
$con=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT fname,lname,contact_info FROM tbl_admin");?>
Related
I am reading and referencing different posts on how to insert if not exists. This is a good thread but I need some additional help.
I need to add a new record with about 10 columns in it, but only insert it if two columns don't match. I also need to do parameter binding on it.
$query = "INSERT INTO Customers (col1,col2,col3,col4,col5,col6)
SELECT * FROM (SELECT ?,?,?,?,?,?) AS tmp
WHERE NOT EXISTS (
SELECT col1 from Customers WHERE uid=? AND pid=?
) LIMIT 1;"
$results = dbQuery($query,(array($val1,$val2,$val3,$val4,$val5,$val6,$uid,$pid)) ;
What am I doing wrong here?
And here is dbQuery call:
function dbQuery($query,$data) {
global $pdo ;
$stmt = $pdo->prepare($query);
$result = $stmt->execute($data) ;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$error = $stmt->errorInfo() ;
if ($result == false) {
var_dump($error) ;
}
return array($result,$error,$rows) ;
}
"?" parameter placeholders aren't named, they're passed by position, so you can't use them more than once.
You could pass uid/pwd twice; but better is to used named parameters passed as a map
(https://www.php.net/manual/en/pdostatement.execute.php)
$query = "INSERT INTO Customers (uid,pid,col3,col4,col5,col6)
SELECT * FROM (SELECT :uid, :pid, :val3, :val4, :val5, :val6) AS tmp
WHERE NOT EXISTS (
SELECT * from Customers WHERE uid = :uid AND pid = :pid
)";
$results = dbQuery($query,(array("uid"=>$uid, "pid"=>$pid, "val3"=>$val3, "val4"=>$val4, "val5"=>$val5, "val6"->$val6)));
Note using the parameter array means all the parameters come through as strings, which may not be what you want. You would have to use bindParam to set specifically typed values.
Best of all would be a stored procedure that allows you to define parameters, use proper binding, and prevent any accidental datatype mismatches.
I'm trying to execute multiple queries, but something is wrong.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
$sql = "
UPDATE tmatria SET par = " . $newpar . ", inde = " . $newinde . " WHERE id =" . $cutid . ";
SELECT * FROM tmatria ORDER BY inde ASC;
SET #i := 0;
UPDATE tmatria SET inde = #i := #i + 1;
";
try {
$db->exec($sql);
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
I want update some columns, then sort table by inde column and finally set inde values to 1 2 3...
I think lines UPDATE tmatria SET par... and SELECT * FROM tmatria ORDER BY inde ASC; are critical, but cannot see what's wrong.
Any help?
You have some fundamental misunderstanding about how to use SQL. You do a SELECT ... ORDER BY, and then you expect the following UPDATE to obey the same ordering. The UPDATE is ordering the table in its natural order, it doesn't pay attention to the SELECT query at all.
And as a matter of coding, there's no need or benefit to executing multiple SQL statements in one call. PDO permits it, but it's not a good habit. You should execute one SQL statement per call. As long as you use the same db connection, the session variable #i will retain its value.
Also use prepared queries when you want to combine PHP variables with a SQL statement; don't concatenate PHP variables into your SQL string.
try {
$sql = "UPDATE tmatria SET par = ?, inde = ? WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$newpar, $newinde, $cutid]);
$sql = "SET #i := 0";
$db->exec($sql);
$sql = "UPDATE tmatria SET inde = #i := #i + 1 ORDER BY inde ASC";
$db->exec($sql);
}
catch (PDOException $e) {
echo $e->getMessage();
die();
}
It also looks like you're trying to renumber inde after every update, to force that column to have consecutive values. This will get slower and slower the more rows you have in the table, right?
You should reconsider why you need that column to have consecutive values.
You need to pass your queries to PDO one at a time. You can still use variables like #i, because PDO will run your queries in order. But it won't run a mess of queries in one call.
I'm trying to create a third table taking two indexes from two different tables for creating a correlation between them using following code:
$query1 = "select iduniverse from universe";
$query2 = "select idfiles from files";
$query3 = "select iduniFiles from uniFiles where filesId = ? and universeId = ?";
$query4 = "insert into uniFiles (filesId, universeId) values (?,?)";
if($stmt1 = $conn->prepare($query1)){
if($stmt2 = $conn->prepare($query2)){
if($stmt3 = $conn->prepare($query3)){
if($stmt4 = $conn->prepare($query4)){
$stmt1->execute();
$stmt1->bind_result($iduniverse);
while($stmt1->fetch()){
$stmt2->execute();
$stmt2->bind_result($idfiles);
while($stmt2->fetch()){
$stmt3->bind_param("ii", $idfiles, $iduniverse);
$stmt3->execute();
$stmt3->store_result();
if($stmt3->num_rows == 0){
$stmt4->bind_param("ii", $idfiles, $iduniverse);
$stmt4->execute();
}
}
}
}
$stmt4->free_result();
}
$stmt3->free_result();
}
$stmt2->free_result();
}
$stmt1->free_result();
But if I put an echo "here\n" after second while loop:
while($stmt2->fetch()){
echo "here\n";
...
When I launch my code I don't see anything on screen output and also table uniFiles remains empty.
I have already checked query via SQL Browser and works without any issue. So I don't understand where is the mistake.
What is wrong in my script?
You can create a join table using INSERT INTO INTO SELECT ...
insert into uniFiles (filesId, universeId)
select iu.iduniverse, if.idfiles
from universe iu
join files if on if.idfiles = iu.idfiles
If there could be duplicates, then combine with INSERT IGNORE
insert ignore into uniFiles (filesId, universeId)
select iu.iduniverse, if.idfiles
from universe iu
join files if on if.idfiles = iu.idfiles
A mysqli connection can only hold a single active prepared statement at a time.
Therefore, you can't have nested prepared statements active on the same connection. You'll have to have a separate connection for each level of the nesting if you need to keep them all active (at least for each one you don't want squashed by the next level's query.
I want to execute these queries
$q1 = "INSERT INTO t1 (id,desc) VALUES (1,'desc');" <br>
$q2 = "SET #last_id = LAST_INSERT_ID();" <br>
$q3 = "INSERT INTO t2 (parentid,desc) VALUES (#last_id, 'somedesc');"<br>
Will this work correctly 3 mysqli_query something like this?
$res = mysqli_query($q1);
$res2 = mysqli_query($q2);
$res3 = mysqli_query($q3);
To start, desc is a MySQL reserved word
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
and must be wrapped in backticks if you're going to decide on using it, without renaming it to something else than desc, say description for instance.
Therefore, you will need to change it to the following, assuming your DB connection is established, and using $con as an example, which you haven't shown us what your DB connection is.
$q1 = "INSERT INTO t1 (id,`desc`) VALUES (1,'desc')";
$q2 = "SET #last_id = LAST_INSERT_ID()";
$q3 = "INSERT INTO t2 (parentid,`desc`) VALUES (#last_id, 'somedesc')";
minus all of your <br> tags, since you are inside PHP, unless that wasn't part of your code, but in trying to format your code in your question.
Sidenote: Your semi-colons were misplaced.
and passing DB connection to your queries:
$res = mysqli_query($con,$q1);
$res2 = mysqli_query($con,$q2);
$res3 = mysqli_query($con,$q3);
Plus, adding or die(mysqli_error($con)) to mysqli_query() to check for possible errors in your queries.
At the moment I have a script where I add data to the database.
Once the data is entered I would like to get the get the row straight away.
For example if I have a query like this where I have two seperate:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."'";
$query = $this->db->query($sql);
$sql = "SELECT * FROM table";
$query = $this->db->query($sql);
return $query->db->row;
I want to be able to make get that database row instantly after inserting it. Will I have to make a whole new query or is there a quicker way? I am using OpenCarts API if that helps.
Thanks
Peter
INSERT INTO table (a,b,c) VALUES ('a','b','c');
SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();
PHP:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."';";
$sql .= "SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();"
$query = $this->db->query($sql);
return $query->db->row;