Getting record from another table with id recognition - php

there are tables artist, track, & etc
in the artist table there is :
id
name
cover
desc
and in the track table there is :
id
name
desc
artistid
so if i goto track.php?id=1 and then they print
id
name
desc
artistid i want to make this show the record from artist table with id recognition
and can you show me how to make multiple filter from recordset. because i have field "pubid" when the value is 1 this mean publish and then if the value is 2 this mean unpublish
sorry bad english
thx u so much

Have a look at SQL Join. In order to only get records which may be published, you'll have to add another WHERE clause. Like:
SELECT name, desc FROM track WHERE id = $id AND pubid = 1;

track.php?id=1
or
track.php?id=1&pubid=1
track.php?id=1&pubid=2
<?php
if (isset($_GET['id'])) {
$artistid = $_GET['id'];
if (isset($_GET['pubid'])) {
$pudid = $_GET['pubid'];
$sql = "select `id`, `name` from `track` where `artistid` = {$artistid} and `pubid` = {$pupid} order by `desc`";
} else
$sql = "select `id`, `name` from `track` where `artistid` = {$artistid} order by `desc`";
$query = mysql_query($sql);
while (($row = mysql_fetch_array($query)) !== false) {
echo $row['name'];
}
}

Related

Get applicants from Table 1 and compare id and get user details from Table 2 Using PHP

Ok so I have two Tables
Applicant list - this shows all applicants
User Table
Now I'm Providing news_id by Post method and I want to list details of all users(email,mobile,username) where the value for user_authToken and user_authtoken is same. Can Someone help me out with this logic using PHP.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile,
FROM appliers_list,user
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();
First of all, your naming is very inconsistent, it's hard to read and understand.
Second, please use prepare statement, otherwise you open your system to SQL injection.
$news_id = $_POST['job_id'];
$stmt = $con->prepare("SELECT email, mobile, user_name
FROM users
WHERE user_authtoken in (select user_authToken from appliers_list where news_id = ?)");
$stmt->bind_param("i", $news_id);
$stmt->execute();
$resultSet = $stmt->get_result();
while($row = $resultSet->fetch_assoc()) {
// data manipulation here
}
you can use left join to get record from both table :
$job_id = !empty($_POST['job_id']) ? intval($_POST['job_id']) : 0;
$resultSet = $con->query("SELECT appliers_list.*,users.email
FROM appliers_list
left join users on appliers_list.user_authToken = users.user_authToken
WHERE news.news_id = '$job_id'
ORDER BY news.id DESC
");
$rows = $resultSet->fetch_assoc();
You didn't specify a relationship between the user and appliers_list tables, so you're getting all rows in user. You also have an extra comma at the end of the SELECT list.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile
FROM appliers_list
JOIN user ON appliers_list.user_authToken = user.user_authToken
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

How select random column value from Mysql database using PHP

I'm trying to fetch random column from database using Rand() function.
It's returning random value but many time it is returning duplicate.
This is what my database table look like.
Column
Type
Null
Default
no
int(30)
No
postid
varchar(100)
Yes
NULL
byuser
varchar(32)
Yes
NULL
likeslimit
int(30)
No
createdon
date
No
And this is what my PHP code is.
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
echo $row['postid'];
}
}
I want it to always return random never the same till the end of data reached.
Don't use loop and condition you want only 1 limit try this
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
$row = mysqli_fetch_assoc($query)
echo $row['postid'];
This is the way RAND in mysql works and will repeat the results from time to time. But you can achieve such functionality by using mysql with php.
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int)$row['postid'];
if((int) $foundId === 0) { // NO records left in cacheTable then fill it up again
mysqli_query($mysql, "INSERT INTO cacheTable (postid) SELECT postid FROM history");
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int) $row['postid'];
}
mysqli_query($mysql, "DELETE FROM cacheTable WHERE postid=".$foundId); // DELETE the record
$query = mysqli_query($mysql, "SELECT * FROM history WHERE postid=".$foundId);
$result = mysqli_fetch_assoc($query);
cacheTable will have only one column - ID (primary key) which will hold the corresponding ID (primary key) from history. cacheTable structure:
|------
|Column|Type|Null|Default
|------
|postid|varchar(100)|Yes|NULL
|-----
cacheTable will fill with all the ids from history table (it will be done once the cacheTable is empty). You will select rand result from the cacheTable and you will delete it then so it will not appear in the next selects. When we are out of records in cache table it will populate again.
NB: this approach has one major drawback - when you have new entries in history table they won't be available in cache table until it is empty and filled again.
This is the code Samir Nabil Suggested :
session_start();
$_SESSION['dupes'] = array();
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
if (!in_array($row['postid'], $_SESSION['dupes'])) {
echo $row['postid'];
$_SESSION['dupes'][] = $row['postid'];
}
}
}

Display Each Row Where URL Variable Corresponds With Database ID

I have a URL that is dynamically generated:
https://mywebsite.co.uk/report.php?taskid=25&rep=1&rep=2&rep=3
I can retrieve the variable for the task ID and rep fine:
if (isset($_GET['taskid'])) { $taskid = $_GET['taskid']; }
if (isset($_GET['rep'])) { $referenceID = $_GET['rep']; }
What I'm trying to do is create an SQL statement on the page that selects a row based on the rep number in the URL. For example:
SELECT TASK_ID, ID, NAME FROM mytable WHERE TASK_ID = $taskid AND ID = $referenceID
However, when I echo the result of $referenceID it is always the last rep, so in this case 3. How do I select the rows from the database where ID = 1,2 & 3?
I then want to display each row, so it would be something like:
<table>
$result = mysqli_query($con,"SELECT TASK_ID, ID, NAME FROM mytable WHERE TASK_ID = $taskid AND ID = $referenceID");
while($row = mysqli_fetch_array($result))
{
$ID = $row['ID'];
$NAME = $row['NAME'];
print "<tr><td>$ID</td><td>$NAME</td></tr>";
}
</table>
This query should return 3 rows in the table with the ID AND NAME in each row.
Your help would be appreciated.
First, you need to change your parameter name from rep to rep[]
This will cause PHP $_GET['rep'] to return an array.
Then you need to implode the array to obtain a string with commas:
if (isset($_GET['rep'])) {
$referenceID = implode(',',$_GET['rep']);
}
You have to change your SQL syntax to this:
SELECT TASK_ID, ID, NAME FROM mytable WHERE TASK_ID = $taskid AND ID IN ($referenceID)
try this query
$result = mysqli_query($con,"SELECT TASK_ID, ID, NAME FROM mytable WHERE TASK_ID = $taskid AND (ID <= $referenceID and ID>= 1)");
You should use array-style URL parameters, e.g.
https://mywebsite.co.uk/report.php?taskid=25&rep%5B%5D=1&rep%5B%5D=2&rep%5B%5D=3
Then $_GET['rep'] will be an array, and you can do:
$referenceIDs = implode(',', array_map(array($con, 'real_escape_string'), $_GET['rep']));
$sql = "SELECT TASK_ID, ID, NAME
FROM mytable
WHERE TASK_ID = $taskid
AND ID IN ($referenceIDs)";

MySQL next and prev record issue

I made this php script and i am tryin to make it to return next and previus row, but there is one problem when i input my id the script return different thing for example :
This is my DB
ID String
1 Test 1
2 Test 2
3 Test 3
4 Test 4
So if i put ./index.php?id=1 this returns the result of id=2 and id=2 => id=3 and so on...
My question is how to fix it to return accurate result not +1. I tried with <= or => operators the result is correct, but then my links doesnt work.
Here is the script
<?php
if(isset($_GET['id']))
{
$id = (int)$_GET['id'];
}else
{
$id = 0;
}
$stmt1 = $db->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt1->bindValue(1,$id);
$stmt1->execute();
$row = $stmt1->fetch();
$stmt2 = $db->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DESC LIMIT 1");
$stmt2->bindValue(1,$id);
$stmt2->execute();
$row = $stmt2->fetch();
echo $row['id'];
echo "<br/>";
echo $row['string'];
?>
I am not sure if the problem as silly as that, but I have no other explanation.
To have your page you need to make 3 selects:
to get current page data
to get prev id
to get next one
But I can see only 2 selects
So, you have to select data for the very page to show
if(isset($_GET['id']))
{
$sql = "SELECT * FROM records WHERE id = ?";
$stm = $db->prepare($sql);
$stm->execute(array($_GET['id']));
} else {
$sql = "SELECT * FROM records ORDER BY id ASC LIMIT 1";
$stm = $db->query($sql);
}
$row = $stm->fetch();
and now you can go for getting prev and next ids
$sql = "SELECT id FROM records WHERE id < ? LIMIT 1";
$stm = $db->prepare($sql);
$stm->execute(array($row['id']));
$prev = $stm->fetchColumn();
$sql = "SELECT id FROM records WHERE id > ? LIMIT 1";
$stm = $db->prepare($sql);
$stm->execute(array($row['id']));
$next = $stm->fetchColumn();
i am tryin to make it to return next and previus row
There is no such thing as "previous" or "next" row in a table. Without explicit ordering, tables must be considered as unordered set of rows. And you shouldn't rely on auto_increment field to be sequentially numbered. For example:
because there was interleaved insert on the table,
because the server is allowed to reuse auto_increment after row deletion.
You probably have to modify your table structure to add a sequence number:
CREATE TABLE tbl (id in primary key not null auto_increment,
sequence_number int unique,
value char(40));
While inserting your data you might rely on something like that:
INSERT INTO tbl (sequence_number, value)
VALUES (SELECT COUNT(*) FROM tbl, ?)
And the query for the "next" and "prev":
SELECT * FROM tbl WHERE sequence_number = ?-1 OR sequence_number = ?+1
ORDER BY sequence_number;

Categories