SQL/PHP - Join 2 Tables with data from other table - php

This is the query for SQL statement
UPDATE TrendingEvents
SET Name = ?, Image = ?, Date = ?, EventCategory = ?
WHERE ID = ?;')
I would like to access the ID of the other table within my TrendingEvents table. This is the example I've done although it doesn't fully work;
UPDATE TrendingEvents INNER JOIN
Events AS eID
ON TrendingEvents.ID = Events.ID
SET Name = ?, Image = ?, Date = ?, EventCategory = ?
WHERE eID = ?;')
I would like to update the TrendingEvents table with the ID column from Events table.
The error I'm getting from my statement is
Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'Name'
Which just shows that I've poorly designed my query.

Both tables seem to contain a column called Name. You need to properly prefix the fields with the table name, like :
UPDATE
TrendingEvents AS t
INNER JOIN Events AS e
ON t.ID = e.ID
SET
t.Name = ?,
t.Image = ?,
t.Date = ?,
t.EventCategory = ?
WHERE e.eID = ?

You have misused the table alias, so your query should not even compile. Try this:
UPDATE TrendingEvents te INNER JOIN
Events e
ON te.ID = e.ID
SET te.Name = ?,
te.Image = ?,
te.Date = ?,
te.EventCategory = ?
WHERE e.eID = ?;

Related

Using PDO to look up records in one table and append data to another

I have 2 tables, each with 3 columns
Table1 has a columns, id, code and name
Table2 has a columns, id, name and table1id
When new records are created in Table2 the column table1id needs to be filled out with the id Table1 has for that name.
The query must look at the last id created in Table2 and match the Table2 name column with the name in Table1 and then append the id associated with the name to Table2.
How can this be done correctly? The following is the PDO structure I have:
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE `Table2` SET `table1id` = :last_id_0) WHERE `id` = :last_id');
$stmt->execute([
]);
The variable :table1id should be based on the last created record in Table2 but I am unsure with how to continue from here.
This is a visual representation of the two tables described:
UPDATE:
Last inserted id is assigned to the variable $last_id like this:
$stmt = $conn->prepare( ' INSERT INTO `Table2` (`name`)
VALUES (:name ) ' );
$stmt->execute([
'name' => $_POST['name']
])
$last_id = $conn->lastInsertId();
I think I know what you want. I assume table1 has already existed for a long time, and all you do is insert a row into table2. You can use an INSERT INTO SELECT like this:
$stmt = $conn->prepare('INSERT INTO `Table2` (`name`, `table1id`)
SELECT `name`, `id`
FROM `table1`
WHERE `table1`.`name` = :name');
$stmt->execute(['name' => $_POST['name']]);
This query inserts a new row into table2 using the selected name and id from table1. The selected record in table1 is the one with the matching name.
Please note that this will only work if the names in table1 are unique.
if you need to change table2.table1id according to table1.name.
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE Table2
INNER JOIN table1 ON Table1.name = Table2.name
SET Table2.table1id = :id
WHERE Table1.name = :name');
$stmt->execute(['id'=>$last_id , 'name' => $_POST['name']])
Why not to write a query which is just verbatim your requirement?
look up records in one table
$stmt = $conn->prepare('SELECT id from table1 where name=?');
$stmt->execute([$_POST['name']]);
$row = $stmt->fetch();
append data to another
$stmt = $conn->prepare('INSERT INTO `Table2` (`table1id`) VALUES (:t1id)');
$stmt->execute(['t1id' => $row['id']);
Note that it's a very bad idea to duplicate data in the tables, so it's best to keep the name only in table1. You can always have it for table2 using JOIN.

Is there a way to combine mysqli queries or give them a sequence for optimization?

I wonder if it is possible to optimize my queries to avoid having to send ten requests, to check if three main tables and two composite tables has the needed elements and if not then insert them.
("Composite table" is what i call a table that holds two primary keys that both are a reference to the primary key in another table, cause i do not know the correct term)
So i have tried to see if i can get all the needed ids from the three main tables in one query, but i can not it it to work.
Here is some of the things i have tried.
select t1.a AS EID, t2.a AS CID, t3.a AS IID from (select ID as a from Events where event = "test3") as t1, (select ID as a from Coordinates where Coordinates = "10.22,14.15") as t2, (select ID as a from Intervals where Interval = "From 12:15 To 18:30") as t3;
SELECT ID AS eid FROM Events WHERE event = "test3" UNION ALL SELECT ID AS cid FROM Coordinates WHERE Coordinates = "10.22,14.15" UNION ALL SELECT ID AS iid FROM Intervals WHERE Interval = "From 12:15 To 18:30"
And this is what i am currently doing
if(!empty($this->event) && $this->event!== false){
$sql = "SELECT ID FROM Events WHERE event = ?";
$values = array($this->event);
$db->setQuery($sql, $values);
$db->singleFetch();
if($db->getResults() == 1){
$eid = $db->getFetch()[0]['ID'];
}
else{
$sql = "INSERT INTO Events (event, Description) VALUES (?, ?)";
$values = array($this->event, $this->description);
$db->setQuery($sql, $values);
$db->singleQuery();
$eid = $db->getLast();
}
}
//I am doing this for all three main tables,
//to get the ids needed for me to be able to do this.
if(isset($eid) && isset($cid)){
$sql = "SELECT count(*) FROM EC WHERE EID = ? AND CID = ?";
$values = array($eid, $cid);
$db->setQuery($sql, $values);
$db->singleFetch();
if($db->getFetch()[0]['count(*)'] == 0){
$sql = "INSERT INTO EC (EID, CID) VALUES (?, ?)";
$values = array($eid, $cid);
$db->setQuery($sql, $values);
$db->singleQuery();
}
}
//Which i then do for both composite tables
Either i get my fetch array with every possible combination or i do not even get my fetch array and other times i get it but with two of the same event id and nothing else.
You can write the stored procedure in MySQL for this and then you need to call that stored procedure

data not coming in proper order from table using php

I am trying to insert data from feed into the database using Zend and also adding a column date_updated in table so that whenever the article in feed is updated the column also gets updated. But the problem is, the first article is being inserted earlier and thenafter the others. So, when I am trying to do a select of top 10 articles based on date_updated DESC, the article being inserted at last is getting on top and if i use ASC then the older ones are getting selected. Please suggest how do i proceed. The query I am writing is:
$sql = "INSERT INTO news_article
(original_article_id, headline,summary, keywords, link, section, topic, date_published, date_updated, content, source_id)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE
original_article_id = ?,
headline = ?,
summary = ?,
keywords = ?,
link = ?,
section = ?,
topic = ?,
date_published = ?,
date_updated = ?,
content = ?,
source_id = ?";
$values = array(
"original_article_id"=>$id,
"headline"=>$item->title,
"summary"=>$summary,
"keywords"=>$keywords,
"link"=>$item->link,
"section"=>"property",
"topic"=>"property",
"date_published"=>$formattedPubDate,
"date_updated"=>$currentDate,
"content"=>$data,
"source_id"=>"3"
);
$result = $db->query(
$sql,
array_merge(array_values($values), array_values($values))
);
and thenafter i am using
SELECT * FROM news_article ORDER BY date_updated DESC LIMIT 10
use below query
SELECT * FROM news_article ORDER BY date_updated DESC LIMIT 0,10
After limit we need to pass offset and number of records to fetch.

INSERT with two SELECT statements

Here is what I am currently trying but I am receiving an mySQL error:
mysql_query ("INSERT INTO profile_tag (profile_id, tag_id)
(SELECT profile_id FROM profile WHERE username = '$username'),
(SELECT tag_id FROM tag WHERE tag = '$music' OR tag = '$sports' OR tag = '$tech')");
I am able to complete an INSERT using a single SELECT statement however, not two.
The error I receive:
Query is invalid: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')' at line 1
Much like the error says, the syntax is incorrect. The values of the insert has to match the number of values in the column definition.
INSERT INTO profile_tag (profile_id, tag_id)
SELECT
profile_id, tag_id
FROM
profile
CROSS JOIN tag
WHERE
username = ?
AND tag IN (?, ?, ?)
Note that this will insert multiple rows if a tag value is found for each of the inputs, but I believe that is what you want.
You can use VALUES clause
insert into profile_tag(user_id, tag_id) values
((select id from users where username = 'alice'),
(select id from tags where tag = 'music'));
http://sqlfiddle.com/#!2/76439/1/0
mysql_query ("INSERT INTO profile_tag (profile_id, tag_id)
(SELECT profile.profile_id, tag.tag_id FROM profile LEFT JOIN tag ON 1 WHERE profile.username = '$username' AND tag.tag IN ('$music', '$sports', '$tech'))");

Help with logic

I have a number of objects. They can be sorted into groups. When a user "drags" an object into a group, I INSERT a record into my db
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES
($groupID, $itemID, $projectID, $userID)
There can be multiple objects in the same group and those objects can be moved from one group to another. When I move the objects into another group, I don't need to create another record, but rather only update group_id.
EDIT:
I think I need to do something like this afterall:
table structure
t1.id
t1.group_id
t1.item_id
t1.project_id
t1.user_id
if ("SELECT id, group_id FROM t1
WHERE item_id = $itemID
AND project_id = $projectID
AND user_id = $userID")) {
// if found
UPDATE t1
SET group_id = $groupID
WHERE id = $ID
} else {
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES ($groupID, $itemID, $projectID, $userID)
It sounds like u should place a if statement when moving from a group to another group to update only the object being move. Say for instance if I am selecting an object from its initial(beginning) space I would add the insert statement. If I am moving an object that has already been grouped to another group I would add an update statement. Finally if I am taking an item out of all groups completely I would issue a delete statement that will remove the object from the table.
pseudo code
if object = new
{
INSERT INTO t1 (group_id, item_id, project_id, user_id)
VALUES ($groupID, $itemID, $projectID, $userID)
}
if object = group
}
UPDATE t1
SET group_id = $newgroupID
WHERE item_id = $itemID;
}
if object = banned
}
delete from t1 where item_id = $itemID
}
This sequence of code should be placed on each container that you are dragging your objects to so that it can check for the proper requirements.
You can do it in one query using insert ... on duplicate key update.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html for details.
Assuming that item_id is a key, you can do
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES
($groupID, $itemID, $projectID, $userID)
ON DUPLICATE KEY UPDATE group_id = $groupID
I suggest you to add a surrogate primary key so you can you can identify uniquely every row. Then you can make an update like this:
UPDATE t1 SET group_id = $newgroupid WHERE id = $objectid;

Categories