I have two tables that I'm trying to join into a new table. I have a "users" table, a "tasks" table and I have a blank "user_tasks" table. I'm trying to join them into the "user_tasks" table.
Here are my tables.
users = user_id, first_name, last_name
tasks = task_id, task_description
user_tasks = ut_id, ut_user_id, ut_first_name, ut_last_name, ut_task_id, ut_task_description.
Here is my PHP & SQL query. I'm not sure what is wrong. I get an undefined index. Do I need to add hidden inputs on my HTML form? Any help would be appreciated.
<?php
if(isset($_POST['submit'])){
$user_id = $_POST['user_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$task_id = $_POST['task_id'];
$task_description = $_POST['task_description'];
$ut_id = $_POST['ut_id'];
$ut_user_id = $_POST['ut_user_id'];
$ut_first_name = $_POST['ut_first_name'];
$ut_last_name = $_POST['ut_last_name'];
$ut_task_id = $_POST['ut_task_id'];
$ut_task_description = $_POST['ut_task_description'];
$join_query = "SELECT users.user_id, users.first_name, users.last_name, tasks.task_id, tasks.task_description FROM users, tasks INNER JOIN user_tasks ON users.user_id = user_tasks.ut_id INNER JOIN user_tasks ON tasks.task_id = user_tasks.ut_id INSERT INTO user_tasks (ut_user_id, ut_first_name, ut_last_name, ut_task_id, ut_task_description) VALUES ($user_id, $first_name, '$last_name', '$task_id', $task_description) WHERE ('$first_name' = '$ut_first_name', '$last_name' = '$ut_last_name', $task_id = $ut_task_id, '$task_description' = '$ut_task_description') ";
$result = mysqli_query($connection, $join_query);
}
?>
I think the table('user,tasks') in your select is wrong,maybe the table is 'user_tasks'
You have two concatenated queries,select + insert
, try this:
1- insert + select separate:
$join_query = "SELECT users.user_id, users.first_name,
users.last_name, tasks.task_id,
tasks.task_description FROM users
INNER JOIN user_tasks ON users.user_id = user_tasks.ut_user_id
/*users.user_id = user_tasks.ut_id*/
INNER JOIN tasks ON task.task_id=user_task.ut_task_id";
$result = mysqli_query($connection, $join_query);
AND Insert After,Insert does not use where:
$insert_query="INSERT INTO user_tasks (ut_user_id, ut_first_name, ut_last_name,
ut_task_id, ut_task_description)
VALUES ($user_id, '$first_name', '$last_name',
'$task_id', '$task_description')";
mysqli_query($connection,$insert_query) or die(mysqli_error($connection));
2- INSERT with SELECT:
$query="INSERT INTO user_tasks (ut_user_id, ut_first_name, ut_last_name,
ut_task_id, ut_task_description)
SELECT users.user_id, users.first_name,
users.last_name, tasks.task_id,
tasks.task_description FROM users
INNER JOIN user_tasks ON users.user_id = user_tasks.ut_user_id /*users.user_id = user_tasks.ut_id*/
INNER JOIN tasks ON task.task_id=user_task.ut_task_id";
mysqli_query($connection,$query) or die(mysqli_error($connection));
Related
Is this possible to be done with SQL?
I need to make a SQL selection depending if a $query is false WHERE (u.id_user = ".$userId." OR fu.id_user = ".$userId." OR ff.id_user = ".$userId.")" ELSE "$query";
That's my starting point where both conditions have to be met:
$validatedSearchData = array(
"q"=>strip_tags($_GET["q"])
);
$query= " AND a.tags LIKE ".lib::$db->qstr("%".$validatedSearchData["q"]."%");
$feed = lib::$db->GetAll("SELECT SQL_CALC_FOUND_ROWS
a.*,
u.name,
fu.id_user AS fu_user_id,
ff.id_followed_user AS ff_user_id
FROM feed AS a
LEFT JOIN userfollow AS fu ON a.id_author = fu.id_user
LEFT JOIN userfollow AS ff ON a.id_author = ff.id_followed_user
INNER JOIN user_profiles AS u ON a.id_author = u.id_user
WHERE (u.id_user = ".$userId." OR fu.id_user = ".$userId." OR ff.id_user = ".$userId.")" . $query. "
GROUP BY a.id_article
");
Change this line
$query= " OR a.tags LIKE ".lib::$db->qstr("%".$validatedSearchData["q"]."%");
replace OR in the place of AND
I have two queries that count the number of data for both "artists" and "groups" in my database. I want to display a message if there is data to display for either artists or groups (or both), and if the data returns 0 for both of them then not to display anything.
I have the following code which doesn't seem to work:
<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {
} else {
echo "There is information to display.";
}
?>
Below are the queries I have:
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$numrowsartists = mysql_fetch_assoc($res);
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$numrowsgroups = mysql_fetch_assoc($res);
Thanks in advance. I'm sure it's probably a super basic fix but I'm still very new to php and would appreciate some help.
You should getthe value frorm the row eg using alias for column name
$query = "SELECT COUNT(*) as num_artists FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsartists = row['num_artists'];
$query = "SELECT COUNT(*) as num_groups FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsgroups = row['num_groups'];
There are several solutions, the easiest being the following:
if($numrowsartists[0]+$numrowsgroups[0] > 0)
However, as people have said, you shouldn't use mysql_* functions anymore.
Assuming the ID is user input, you should really use prepared statements.
Also, you can handle both tests in a single query:
$stmt = $con->mysqli_prepare("SELECT COUNT(1) as `count` FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = ?");
$stmt->bind_param('i',$id);
$stmt->execute();
if($stmt->get_result()->fetch_array()[0] > 0){
...
}else{
//message that nothing was found
}
I want to select data from a table called tbl_users using a value from another table called mergeing and column called donator_1.
I tried the following:
$result = $DBcon->query("SELECT tbl_users.username, tbl_users.email, tbl_users.Phone_number FROM tbl_users,mergeing WHERE mergeing.donator_1= tbl_users.user_id AND mergeing._id = 6");
while($row = $result->fetch_array()) {
echo '<b>' . $l['user_id'] .'</b><b>' . $l['username'] . '</b>';
}
You can try nested queries:
SELECT username, email, Phone_number
FROM tbl_users
WHERE user_id = (SELECT donator_1 FROM mergeing WHERE _id = 6 )
or an inner join :
SELECT username, email, Phone_number
FROM tbl_users
JOIN mergeing ON tbl_users.user_id = mergeing.donator_1
WHERE mergeing._id = 6
Instead of wanting the whole table i only want one result based on a link.
This works:
$BANDID = intval($_GET['BANDID']);
$sql = "SELECT
BANDID,
NAAMBAND,
CONTACTBAND,
GENRE,
OMSCHRIJVING,
LEDEN,
PLAATS,
PRIJS,
BOEKERID,
WEBSITE,
YOUTUBE,
NOTITIES
FROM
`BANDS`
WHERE
BANDID = $BANDID";
$BANDID is get by clicking a link on a previous page, but i wanted it combined the above
$sql = "SELECT
NAAM,
BANDID,
NAAMBAND,
CONTACTBAND,
BOEKERID
FROM
`BANDS`
INNER JOIN
`adres`
WHERE
`BANDS`.BOEKERID = `adres`.id ";
but this doenst work:
$BANDID = intval($_GET['BANDID']);
$sql1 = "SELECT
NAAM,
BANDID,
NAAMBAND,
CONTACTBAND,
BOEKERID
FROM
`BANDS`
INNER JOIN
`adres`
WHERE
`BANDS`.BOEKERID = `adres`.id
WHERE
BANDID = $BANDID";
Please help me further, thks
You should use ON and combine it with WHERE like this:
$sql1 = "SELECT NAAM,BANDID, NAAMBAND, CONTACTBAND, BOEKERID
FROM `BANDS` INNER JOIN `adres`
ON `BANDS`.BOEKERID = `adres`.id
WHERE BANDID=$BANDID";
That's how you do proper joins.
WHERE `BANDS`.BOEKERID = `adres`.id WHERE BANDID=$BANDID";
replace second where with AND
WHERE `BANDS`.BOEKERID = `adres`.id AND BANDID=$BANDID";
You need to change to proper join syntax. Every join needs an ON clause and then you can put your WHERE clause below that.
$sql1 = "SELECT NAAM,BANDID, NAAMBAND, CONTACTBAND, BOEKERID
FROM `BANDS`
INNER JOIN `adres`
ON`BANDS`.BOEKERID = `adres`.id
WHERE BANDID=$BANDID";
I am trying to refactor this code a bit. Originally I had two different models, both extending MY_Model. However, most of the code was repetitive so now I am having First_model extend MY_Model and Second_model extends First_model. I cleaned up most of code from Second_model that it inherits from First_model, but I have several methods within Second_model that are only slightly different from the same method in First_model. Consider the following code:
First_model
class First_model extends MY_Model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
}
Second_model
class Second_model extends First_model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date("Y");
$month = date("n");
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
UNIX_TIMESTAMP(post.ts_created) ts_created,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
SUM(ka.karma) monthly_karma,
post.answer_status_flags
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (
SELECT
IFNULL(u_all.id, user.id)
FROM
UserAccounts ua
INNER JOIN Users u ON (u.id = ua.user_id)
LEFT OUTER JOIN Users u_all ON (u_all.facebook_uid = u.facebook_uid)
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year} AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row['id']] = $row;
}
return $functionResults;
}
}
Notice the only thing different is the query in the $sql variable. I am wondering can I somehow make the method in the first model protected and only change the query in the second? Or is there a more efficient way to trim down this code? I have several methods this same thing applies to and it seems a bit much to keep redefining the methods in the new Class.
I would think about pass the $sql as a variable in your models:
In your First Model you would have:
private $sqlPostId = '';
public function __construct() {
$this->sqlPostId = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
}
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
// Here you use the defined variable in the constructor
$query = $this->db->query($this->sqlPostId);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
And then you just have to change the SQL in the construct function in your second Model and go.