I have the following table, named "question".
I want a query that will retrieve the maximum QID from the table where I specify a Pid. Then I want to take the selected value and add 1 to it. I want this to work even if there is no value where Pid is for example 1 or 2.
For example if the max qid is 1 where pid is 1, I want a code to retrieve a 1 and add 1. If I in my query put "WHERE pid=2" and there is no pid=2 in my table, I want it to make qid=1.
I have this code to get the maximum qid-value but it doesn't work.
$qu = mysqli_query("SELECT max(qid) AS id FROM answer_det WHERE WHERE pid = '1' ");
$result = $mysqli->query($qu);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo $row['id'];
}
}
I think you should use ifnull
$qu = mysqli_query("SELECT ifnull(max(qid)+1, 1) AS id
FROM answer_det WHERE WHERE pid = '1' ");
In this way if you try a query for a pid that not exist you get the value 1 otherwise you get the value +1
Related
I have a MySQL DB that resembles the following:
uid suid
1 5
1 6
2 5
5 1
5 2
I am giving it a single unique "uid" via the POST method, call it 1. What I need to do is return all "suid" where $uid "has" suid AND suid (as uid) "has" $uid (as suid.) So, in the above example, the script should only return 5.
I know my first step is
"Select * FROM table Where uid = $uid"
then maybe I have to loop through the results and query the DB WHERE suid = $uid.
I do not know how to do the second query. Any suggestions?
One option here would be to self join, with the join condition being that uid in one table matches suid in the other table, and vice-versa for the suid in the first table.
SELECT
t1.suid
FROM yourTable t1
INNER JOIN yourTable t2
ON t1.uid = t2.suid AND
t1.suid = t2.uid
WHERE
t1.uid = 1
Before applying the WHERE clause, the above query would return two records:
uid | suid (uid not selected)
1 | 5
5 | 1
The WHERE clause then chooses the first record, which is what we want, using the uid parameter which you pass it.
Demo here:
Rextester
this is what I came up with:
$uid = $_POST["UID"];
$myquery = "SELECT * FROM Table WHERE uid = '$uid'";
$result = $conn->query($myquery);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myquery2 = "SELECT * FROM Table WHERE uid = '" . $row['suid'] . "' AND suid = '$uid'";
$result2 = $conn->query($myquery2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
echo $row["uid"].
"!##$";
}
}
}
}
$conn->close();
?>
I feel it is not pretty but it did the trick.
Suppose I have a table TABLE:
NAME ID ...
m -1 ...
f -1 ...
g -1 ...
b -1 ...
z -1 ...
And I want to turn it into:
NAME ID ...
f 1 ...
g 2 ...
m 3 ...
b -1 ...
z -1 ...
You probably get the idea:
select the first 3 rows from the original table (preserving order)
order selected rows by the NAME column.
update selected rows' IDs with their position in the new table (keeping the remaining unselected rows in their original positions).
So (m, f, g) got sorted to (f, g, m) and (b, z) remained (b, z).
Here's how I am trying to do it in PHP:
$count = 0;
$query = "UPDATE TABLE SET ID = $count:= $count + 1 ORDER by NAME DESC LIMIT 3";
mysqli_query($con, $query);
But I don't think I can just go ahead and increment a counter and store its value like that. Any advice?
You can try this :
$limit = 3;
for($count = 0 ; $count < $limit;$count++ ){
$query = "UPDATE TABLE SET ID = $count + 1 WHERE ID = '-1' ORDER by NAME DESC";
mysqli_query($con, $query);
}
$query = "UPDATE TABLE SET ID = '-1' WHERE ID > $limit ORDER by NAME DESC";
mysqli_query($con, $query);
In the above logic :
In the final loop, all the IDs are set to $limit
However the update command outisde the loop will set back IDs to -1 again
First, you can quickly query for the first 3 rows in the table and get the name property only and assign the value in an array.
$sql = "select name from table order by name limit 3"
$query = $mysqli->query($sql);
Now let's construct a helper array:
while ($row = $mysqli->fetch_assoc()) {
$a[] = $row['name'];
}
Now just structure the queries:
foreach($a as $id => $name) {
$query = "update table set id={$id+1} where name='$name' limit 1";
// execute the query
}
Note that I assume that the name is unique so I added the limit 1 directive to tell it stop looking for rows to update once it has found a row.
Also, don't forget that array keys are counting starting from 0, hence we are adding 1 to the $id in the loop.
There may be more elegant solutions but this one is rather easy to understand and use.
In MySQL:
SET #row_number = 0;
update TABLE d
join
(
select
NAME,
#row_number:=#row_number+1 as ID,
from
(select NAME from TABLE limit 3) t
order by
NAME asc
) s on s.NAME = d.NAME
set d.ID = s.ID;
SQLFiddle: http://sqlfiddle.com/#!9/dffecf/1
This assumes NAME is your unique key, otherwise likely best to replace with an Identity column in your table and use that for the update.
This approach may require some syntax changes depending on your DB engine. By doing this in SQL, we only make one pass at the DB. Not a huge deal to iterate in multiple passes with PHP if you're only updating three records, but if it was a 1000, etc.
I am trying to get the first id with a specific date.
So this is my code:
$checkm = "SELECT FIRST(id) FROM times WHERE date='2014-03-07'";
$resultm = mysqli_query($con,$checkm);
I have a table called times and there are some columns. Two of them are date and id.
I am trying to get the first row's id with the date 2014-03-07.
EDIT: Fixed!
$checkm = "SELECT id FROM times WHERE date='2014-03-06' ORDER BY id ASC LIMIT 1";
$resultm = mysqli_query($con,$checkm);
while($row = mysqli_fetch_array($resultm)) {
$resultm1 = $row['id'];
}
You probably want the minimum id.
SELECT min(id)
FROM times
WHERE date = '2014-03-07'
pretty straightforward...
SELECT id FROM times WHERE date='2014-03-07' ORDER BY id ASC LIMIT 1
I have the following query which i am using to pull in data into an html page. The url is something like example.com/sss.php?eventid=1111. So what the query does is it calls the event id and 1 record > than the event id. How would i call the 1 record > than the event id so i can use it for a next button?
$eventid = _GET['eventid']
$resultnext = mysql_query("SELECT tblimage.*, events.*
FROM events LEFT JOIN tblimage ON events.id_user = tblimage.userid
WHERE event_id >= '$eventid'
Order By event_id DESC
LIMIT 2")
The way you have it now if you have the following eventids: 1111, 1112, 1113, 1114, 1115, 1116, 1117. With your query it would return 1116 and 1117. So, I think all you may need to do is change the DESC to ASC. Doing so should produce 1111 and 1112.
EDIT, if you only need the next record for the button then use LIMIT 1 and something like the following:
$eventid = _GET['eventid']
$resultnext = mysql_query("SELECT events.*, tblimage.*
FROM events LEFT JOIN tblimage
ON events.id_user = tblimage.userid
WHERE event_id > '$eventid'
Order By event_id
LIMIT 1");
$nResults = mysql_num_rows($resultnext);
if ($nResults > 0) {
$row = mysql_fetch_row($resultnext);
echo $row[0]; // 1112 would be what is returned if event id was the first field
echo $row[1]; // would be what ever the second field is
<a class="ui-pagination-next"
id="next"
data-ajax="true"
href="eventviewtester.php?eventid=<?php echo $row[0];?>"
style="display:none;"
></a>
} else {
//No Records were returned
}
I am not a PHP expert. I just put together this code based on a search I did. The echo $row[0] shows you how to get the individual data pieces. Use that in conjunction with the button code.
Change LIMIT 2 to the following:
LIMIT 2, 1
this is my script
<?php
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
$id = 1;
}
$random = $conn->query("SELECT * FROM records ORDER BY RAND()");
$row = $random->fetch();
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DSC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
?>
But I have a problem with it. For example i have 4 records in database :
ID String
1 Test-1
2 Test-2
3 Test-3
4 Test-4
the query works fine it gives me the next record but not the id which i put like if i put id=1 returns id 2 or id=2 returns info for id 3 and the result is not accurate. So my question is what should I do id to return correct result not +1. I know it starts to count from 0 and i want to fix that in my script i want to make it to start from 1.
replace this
$id = 1;
by
$id = 0;
or replace this
SELECT * FROM records WHERE id > ?
by
SELECT * FROM records WHERE id >= ?
^--//-will look for id equal to 1 or bigger
why don't you change your query to
EDIT: Query will not work as records are deleted.
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id = ?");
$stmt_1->bindValue(1,$id +1);
$stmt_1->execute();
So you will get the record with the next highest id.
Just a hint to optimize your query.
One further question do you use auto_increment in your table definition. If you do so, you shold keep in mind that this mysql-sequence starts by one to calculate the primary key
Hope it helps