I have a database named "movie_tags" in my site's phpmyadmin. And I have tables "action, sci-fi, romantic, .... " which containst "id" and "type" columns inside 'movie_tags'.
I am trying to get each table name which contains '57' in it's 'id' column with this code using php and mysql. But it shows "unknown column 'id' in 'where clause'" error
Here is my code👇
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'movie_tags'
AND id = '57'
You Can Do Like This
$query1 = mysqli_query($your_connection_to_db, "SHOW TABLES FROM movie_tags");
while ($array = mysqli_fetch_array($query1)){
$query2 = mysqli_query($your_connection_to_db, "SELECT * FROM `".$array[0]."` WHERE id = '57'");
$rows = mysqli_num_rows($query2);
if($rows>0){
//you can do your code here with $array[0]. Example👇
echo "your ".$array[0]." table has 57 in it's id column";
}
}
Related
I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error
Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)
my code for the query is following.
public function bride(){
$query = app(UserDetail::class)->newQuery();
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
$query = $query->rightJoin('users','users_details.user_id','=','users.id');
$request = request();
if(request()->exists('sort')){
$sorts = explode(',',request()->sort);
foreach ($sorts as $sort){
list($sortCol, $sortDir) = explode('|',$sort);
$query = $query->orderBy($sortCol,$sortDir);
}
}
else {
$query = $query->orderBy('id','asc');
}
if($request->exists('filter')) {
$query->where(function($q) use($request){
$value = "%{$request->filter}%";
$q->where('name','like',$value)
->orWhere('father_name','like',$value)
->orWhere('city','like',$value)
->orWhere('mother_name','like',$value);
});
}
$per_page = request()->has('per_page')?(int) request()->per_page : null;
$pagination = $query->paginate($per_page);
$pagination->appends([
'sort'=>request()->sort,
'filter'=>request()->filter,
'per_page'=>request()->per_page
]);
return response()->json(
$pagination
)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','GET');
}
What should I do to get the result. Thanks
Because there are same column name in your tables(gender in user_details and users), you need to specify the table name with the column, so that mysql can find the true column for you,
like this:
$query= $query->where('user_details.gender','LIKE','female');
SQL doesn't know which table you are talking about when you are using Joins - unless you specify table names for each column mentioned in your query.
Replace these lines:
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
with these lines:
$query= $query->where('users_details.gender','LIKE','female');
$query= $query->where('users_details.matrimonial','LIKE','1');
I am trying to make the clone of selected table row. The columns are stored in mapping table and are dynamic. I get the column_name from the first query which is to be used in second query to insert the selected result.
In this case I am getting error as Unknown column '$matches'.
db = new PDO("...");
$statement = $db->query("select column_name from mapping_table");
$list = $statement->fetchAll(PDO::FETCH_COLUMN);
$matches = implode('`,`', $list);
$db1 = new PDO("...");
$db1->query("insert into tbl_user(`$matches`) (SELECT `$matches` FROM tbl_user WHERE id= :id)");
$db1->bindParam(':id', $id);
$result= $db1->execute();
The following works...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
However, when I want to select the content type "venue" from the "type" column in the same database tables, I get errors using the following...
global $user;
$items = array();
$sql = 'SELECT nid FROM {node} WHERE uid = :uid AND type = venue';
$result = db_query($sql, array(':uid' => $user->uid));
foreach ($result as $row) {
$items[] = $row->nid;
}
dsm($items);
DOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'venue' in 'where clause': SELECT nid FROM {node} WHERE uid = :uid AND
type = venue; Array ( [:uid] => 1 )
Im ovbiously not understanding something here. The column is called "type", im not asking it to look for a column called "venue" am i?
When comparing a column to a string you need to wrap the string with quotes, if you dont, the optimizer will see this as a column(unless its a number) . Try this:
$sql = "SELECT nid FROM {node} WHERE uid = :uid AND type = 'venue'"
I have 4 tables, tblstaff, tblgrade, tblperformance and tblcategory. In tblperformance, there are 3 keys. perID is a primary key. staffNo and catID are composite keys.
I use catID as auto increment in tblcategory and staffNo, I fill in by myself for tblstaff. My sql statement has no problem when I run the code.
How can I retrieve staffNo and catID from tblstaff and tblcategory to insert in tblperformance using insert statement in sql?
<?php
$staffNo=$_POST['staffNo'];
$staffName=$_POST['staffName'];
$grade=$_POST['grade'];
$gradePosition=$_POST['gradePosition'];
$gradeDepartment=$_POST['gradeDepartment'];
$catTechnical=$_POST['catTechnical'];
$catOtherTechnical=$_POST['catOtherTechnical'];
$catTechnicalDescription=$_POST['catTechnicalDescription'];
$catOtherTechnicalDescription=$_POST['catOtherTechnicalDescription'];
$catWeightage=$_POST['catWeightage'];
$perReqScore=$_POST['perReqScore'];
$perActScore=$_POST['perActScore'];
$perAction=$_POST['perAction'];
$perOtherAction=$_POST['perOtherAction'];
$perTrainingIlsas=$_POST['perTrainingIlsas'];
$perTrainingPublic=$_POST['perTrainingPublic'];
$sql1="INSERT INTO tblstaff(staffNo, staffName)VALUES('$staffNo', '$staffName')";
$result1=mysql_query($sql1);
$sql2="INSERT INTO tblgrade(grade, gradePosition, gradeDepartment)VALUES('$grade', '$gradePosition', '$gradeDepartment')";
$result2=mysql_query($sql2);
$sql3="INSERT INTO tblcategory(catTechnical, catOtherTechnical, catTechnicalDescription, catOtherTechnicalDescription,catWeightage)
VALUES('$catTechnical', '$catOtherTechnical', '$catTechnicalDescription', '$catOtherTechnicalDescription', '$catWeightage')";
$result3=mysql_query($sql3);
$sql4="INSERT INTO tblperformance(perReqScore, perActScore, perAction, perOtherAction, perTrainingIlsas, perTrainingPublic)
VALUES('$perReqScore','$perActScore', '$perAction', '$perOtherAction', '$perTrainingIlsas', '$perTrainingPublic')";
$result4=mysql_query($sql4);
if(($result1 || $result2) || ($result3 || $result4) == TRUE)
{
echo "<script>alert('Data inserted successfully')</script>";
}
else
{
echo "ERROR";
}
?>
To retrieve data, in your case:
$query = "SELECT * FROM tblcategory ORDER BY catID DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$latestCatID = $row["0"];
}
Where SELECT * FROM tblcategory ORDER BY catID DESC LIMIT 1 gives you the last record you inserted.
With staffNo, you can just use $staffNo
Finally, your insert into tblperformance will look like this:
$sql4="INSERT INTO tblperformance(catID, staffNo, perReqScore, perActScore, perAction, perOtherAction, perTrainingIlsas, perTrainingPublic)
VALUES('$latestCatID', '$staffNo', '$perReqScore','$perActScore', '$perAction', '$perOtherAction', '$perTrainingIlsas', '$perTrainingPublic')";
$result4=mysql_query($sql4);
Be careful with '$latestCatID' and '$staffNo', you don't need the single quotes '' if you are using an integer data type.
I have a movie database where movies are inserted into a table named titles with an AUTO_INCREMENT primary key named titles_id. Users can submit movies anonymously which are inserted into a separate identical table named titles_anon. After reviewing entries in titles_anon I want to insert them into titles but the id column is causing problems
I tried this:
INSERT INTO titles SELECT * FROM titles_anon WHERE
title_id='$title_id';
I either get a duplicate key error, or if the title_id does not already exist in titles it inserts OK but uses the titles_anon id instead of a new AUTO_INCREMENT value which I want.
How do I copy a row between tables when both tables have an AUTO_INCREMENT primary key?
INSERT INTO titles
(column_name1, column_name2, column_name3, column_name4,...)
SELECT title_id, col2, col3, col4,..
FROM titles_anon
WHERE title_id = '$title_id';
You define your fields in SELECT, but omit the PK and add the same fields to INSERT!
You can omit the id column completely, let mysql generate it for you. This need a little longer SQL to specify the exact columns you want to insert.
INSERT INTO titles (columns-other-than-the-primary-key)
SELECT columns-of-the-same-order FROM titles_anon
In PHP you can do something similar to:
$rs = mysql_query("select * from table_orig where RowID=$IDToCopy",$db_conn);
$row = mysql_fetch_assoc($rs);
$sql = '';
$fields = '';
foreach($row as $k => $v){
if($k == "RowID") continue;
$sql .= ",'$v'";
$fields .= ",$k";
}
$sql = "insert into table_copy (".substr($fields,1).") values (".substr($sql,1).")";
mysql_query($sql,$db_conn);
/* copy table with primary key to another table */
$table_old='colaboradores'; // your table old
$table_new='colaboradores2'; //your table new
// sql all columns withou primary key (column_key <> 'pri'
$rs=mysql_query("select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name = '$table_old' and column_key <> 'pri' AND
table_schema = 'your database'");
// get all columns
$rows = mysql_fetch_assoc($rs);
$fields = '';
// mount fields in line
foreach ($rows as $k => $v) {
$fields .= ",$v[0]";
}
// remove first comma
$fields = substr($fields,1);
echo "Sintaxe for Create table in Mysql";
echo "CREATE TABLE $table_new SELECT $fields FROM $table_old ";
echo "Sintaxe for Insert from old table to new table Mysql";
echo "INSERT INTO $table_new $fields SELECT $fields FROM $table_old";