Suppose I defined music as a table and gave it 3 columns: album, artist, and track:
CREATE TABLE music (
id int auto_increment primary key,
album varchar(45) not null,
artist varchar(30) not null,
track int(8)
);
Now I want another table releasedy which contains a column:
'Year' and the table music
I suppose for that I have to bind some row from table music with year from table releasedy in another table. So I can know which year contains which musics. If I'm not wrong I have to do that with foreign key. How should I proceed?
You do not want "a table in a table", instead you want to match records from one table with records from another table in a query. You can create a view on top of this query and use the view later as it if were a regular table.
As you guessed, establish a foreign key relationship, then JOIN the two tables.
There is no "table in a table", only tables and relations between them.
Table releasedy will have 2 columns, musicId & year. musicId is the foreign key to your music table.
Join (as you called bind) these two:
SELECT *
FROM music m
INNER JOIN releasedy r ON m.id = r.musicId
WHERE year = ..
Which is all overkill in this example but it illustrates the "binding" you want.
class Functions {
public function getRows($sql){
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
return $data;
}
public function getMusicData(){
$data = $this->getRows("SELECT * FROM music");
return base64_encode(serialize($data));
}
}
$func = new Functions();
$music = $func->getMusicData();
$sql = "insert into releasedy (id,Year) values (NULL,'".$music."')";
mysql_query($sql);
$id = 'your necessary id'; $read = "select * from releasedy where id = ".(int)$id; $data = mysql_query($read); $musics = unserialize(base64_decode($data['Year'])); foreach($musics as $music){ // do something }
Related
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 an array of tags inserted in my database, and I need to insert them in another table with itemID and tagID.
The thing is that i don't have the tagID - instead I have a TagName with the name. I need to get the tagID so I can insert it afterward, but I'm wondering if this is possible to achieve in one single query.
I mean search for the name, then get its tagID and then insert it the array, or even inserting them one by one would work.
if I understood you, my ways is: create two tables first. If you know better way, please let me know.
Table Tag
id keyword
Table C_Tag
id tag_id user_id
Foreign key Tag(id) Reference C_Tag (tag_id)
<?php
$tag=$_POST['tag_name'] //get the tag name
$current_user=$_POST['users_id'];// get the current user id
include 'db_tag.php';
$stmt = $db->prepare("SELECT keyword, id FROM Tag WHERE keyword = :tag ");
$stmt->bindParam(':tag', $tag);
$stmt->execute();
$row_tag = $stmt->fetchALL(PDO::FETCH_ASSOC);
foreach ($row_tag as $row_tag){
}
//if the keyword exist, only update the C_Tag table
if ($row_tag['term'] == $tag){
$stmt = $db->prepare("SELECT t.id, t.keyword, ct.tag_id, ct.user_id FROM Tag t , C_Tag ct WHERE t.id=ct.tag_id ");
$stmt->bindValue(':current_id',$current_user);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
foreach ($row as $row){
}
$row_id=$row['id'];
$row_tag_id=$row['tag_id'];
$row_user_id=$row['user_id'];
if( $current_user == $row_user_id && $row_id == ! $row_tag_id ){
//make sure same user cannot enter duplicate keyword
$stmt = $db->prepare ("INSERT INTO C_Tag (user_id, tag_id)
SELECT :current_id, id
FROM tag
WHERE keyword=:keyword
");
$stmt->bindValue(':current_id',$current_user);
$stmt->bindValue(':keyword', $tag);
$stmt->execute();
}
} else {
//if the keyword is new, I will insert it into both table
}
?>
this appears to be the solution
How to copy a row and insert in same table with a autoincrement field in MySQL?
insert into zr1f4_k2_tags_xref (id, tagID, itemID) select NULL, tagID, #itemID from zr1f4_k2_tags where name=#tagName
but i cant make it work.
this are the tables
zr1f4_k2_tags
id int(11)
name varchar(255)
published smallint(6)
zr1f4_k2_tags_xref
id int(11)
tagID int(11)
itemID int(11)
I'm trying to insert the ID of the tag related to the tagname and item ID which ill add explicitly. and the id is autonumeric
I'm trying to make a SQL query and I have some problems with it.
CREATE table entries (
id_entry INT PRIMARY KEY,
);
CREATE table entry_date (
entry_date_id INT PRIMARY KEY,
entry_id INT,
entry_price INT,
entry_date TEXT,
);
for each entry, there is several dates.
I'd like to select the entries.entry_id where that entry have, for example, the dates '23/03/2013' and '24/03/2013' linked to it.
The two dates are stored into an array:
$data = array('ci' => '23/03/2013', 'co' => '24/03/2013');
I store the dates in text for practical purpose in my treatment.
I use Zend_Db so my query is constructed like that:
$select = $table->select ()->from ( 'entries' )->setIntegrityCheck ( false );
if ($data ['ci'] != NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );
$select->where ( 'entry_dates.entry_date = ?', $data ['ci'] );
}
if ($data ['co']) {
if ($data['ci'] == NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );}
$select->where ( 'entry_dates.entry_date = ?', $data ['co'] );
}
which gives :
SELECT `entries`.*, `entry_date`.*
FROM `entries`
INNER JOIN `entry_dates`
ON entries.id_entry = entry_dates.entry_id
WHERE (entry_dates.entry_date = '23/03/2013')
AND (entry_dates.entry_date = '24/03/2013')
And, well ... It doesn't work.
When I fetch my $select, I get nothing.
I guess I miss something in my request when I do the WHERE ... AND , what should I do to get the correct output ? The real request being really long, I'd like to avoid another long subselect if possible.
It can be done in two way, either with a self-join on the entry_date table:
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed1
ON entries.id_entry = ed1.entry_id
INNER JOIN `entry_dates` AS ed2
ON entries.id_entry = ed2.entry_id
WHERE ed1.entry_date = '23/03/2013'
AND ed2.entry_date = '24/03/2013'
Or with an aggregate
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed
WHERE ed.entry_date = '23/03/2013'
OR ed2.entry_date = '24/03/2013'
GROUP BY `entries`.entry_id
HAVING COUNT(DISTINCT ed.entry_date)=2
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";
i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!