Get record by id number mysql - php

This is my database structure.
id userid
1 x
2 xx
3 xxx
4 xx
I want to display row no. 3 in php. Only userid by row number.
Result should be :
xxx

Try this
select userid from table where id=3

Simply use this query
SELECT userid FROM table WHERE id=3

This should work
<?php
$connection = new mysqli("localhost", "db_username", "db_password", "db_name");
$result = mysqli_query($connection, "SELECT * FROM `table_name` WHERE `id` = '3' LIMIT 1");
$record = mysqli_fetch_object($result);
echo $record->userid;
?>

look here this answer and sqlfiddle:http://sqlfiddle.com/#!2/f001f/2
mysql:
SELECT id, userid
FROM t
WHERE id=3;
php:
$result = mysqli_query($connection, "SELECT id,userid FROM t WHERE id = 3");

Related

get count of the ids in mysql

I want to count all the entries against id
i have used this query
select count(*) from table1 group by `id`
the problem is my table has 3 records
id A has 2 records
id B has 1 record
when i run this query using php it gives me 2 enteries
$mysqli = new mysqli("localhost","root", "", "db");
$query = $mysqli->prepare("SELECT COUNT(*) FROM `tble1` GROUP by `ID`");
$query->execute();
$query->store_result();
$rowsaff = $query->num_rows;
echo $rowsaff;
EDIT: misunderstand the question.
You have to SELECT the count of the distinct id:
$query = $mysqli->prepare("SELECT COUNT(distinct `ID`) FROM `tble1`");

How to use php variables in mysql query while php variable contains mysql query?

How can I implement something like this in mysql?
$query1 = "SELECT id FROM table WHERE username = 'John'";
$query2 = "SELECT id FROM table WHERE username= 'Parsa'";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
$result = mysql_query($query) or die('Query faild'.mysql_error());
$myrecord = mysql_fetch_assoc($result);
Try this
$query1 ="SELECT GROUP_CONCAT(id) FROM table WHERE firstname in('John','Parsa')";
$query = "SELECT * FROM table WHERE id IN ($query1)";
you have two identical queries , you could just have one . and use IN , not BETWEEN.
You can put those 3 queries in to one query:
$query = "SELECT * FROM table WHERE id
BETWEEN
( SELECT id FROM table WHERE firstname = 'John' GROUP BY id )
AND
( SELECT id FROM table WHERE firstname = 'Parsa' GROUP BY id )
";
although your query doesn't mean anything; you need "()" for subqueries to work.
$query1 = "(SELECT id FROM table WHERE username = 'John')";
$query2 = "(SELECT id FROM table WHERE username= 'Parsa')";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
u can use a subselection:
SELECT * FROM table WHERE id BETWEEN ($query1) AND ($query2)
But be careful: The Subselection result must be an Integer.

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;

MySQL / PHP Not inserting correct amount of entries

Hopefully this will be quite simple for someone.
I have the following code:
<?php
// Connects to your Database
mysql_connect("localhost", "xxxxx", "xxxxx") or die(mysql_error());
mysql_select_db("xxxxx") or die(mysql_error());
require("../includes/common.php");
require("admin_header.php");
require("admin_menu.php");
$query = "Truncate TABLE pt_menutitles";
$result = mysql_query($query) or die(mysql_error());
// Menu Headers for Category
$data = "select a.menuheader, a.total from(SELECT distinct (menuheader),count(*) as total FROM `pt_products` WHERE `menuheader` <> '' group by `menuheader` order by total desc limit 4) a order by a.menuheader";
$result = mysql_query($data) or die(mysql_error());
while($info = mysql_fetch_array($result))
{
$menudata = "select a.subcategory, a.menuheader,a.totcount FROM(SELECT distinct (subcategory),menuheader,count(*) as totcount FROM `pt_products` WHERE `menuheader`='".$info['menuheader']."' AND subcategory <> ''group by `subcategory` order by totcount desc limit 4) a order by a.subcategory";
$menuresult = mysql_query($menudata) or die(mysql_error());
while($menuinfo = mysql_fetch_array($menuresult))
{
$sql = "Insert into pt_menutitles (menu, title, totalcount) select '".$menuinfo['menuheader']."','".$menuinfo ['subcategory']."','".$menuinfo ['totcount']."'";
$result = mysql_query($sql) or die(mysql_error());
}
}
?>
Basically I take the top 4 menu titles that have the most items in them, then select the top 4 subcategories in them titles and insert them into a table.
What is happening though is that i'm onlyt getting Menu Title 1 and Subcategories 1 to 4 inserted into my table.
It's as though the the loop is ending after the first time round?
Any advise would be great!
Cheers
Chris
This line replaces your existing result and ends the loop. Use any other (non-existing) variable name, but not $result.
$sql = "Insert into pt_menutitles (menu, title, totalcount) select '".$menuinfo['menuheader']."','".$menuinfo ['subcategory']."','".$menuinfo ['totcount']."'";
$result = mysql_query($sql) or die(mysql_error());

MySQL Update Query - By Row Number

I'd like to update a row in a MySQL table when a specific row number is reached
This is a little confusing since , the real row number of the record isn't a column in the table.
And there's no question of iterating over rows , since we're not iterating over an array as in mysql_fetch_array()
So , if I'd like to update - say the 3rd row of the table , what would the query be like?
I'm a noob at MySQL
Thanks a ton for your help ! :D
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
$query = "SELECT MyColoumn FROM Mytable";
$result = mysqli_query($link, $query);
$row_needed = 3; //Your needed row e.g: 3rd row
for ($i=1,$i=$row_needed,$i++) {
$row = mysqli_fetch_array($result);
}
// now we are in 3rd row
$query = "UPDATE MyColumn FROM MyTable SET MyColumn = '".$MyColumnUpdate."' WHERE MyColumn = '".$row['MyColumn']."' ";
$result = mysqli_query($link, $query);
...
Try this query
UPDATE
tbl a,
(Select
#rn:=#rn+1 as rowId,
tbl.*
from
tbl
join
(select #rn:=0) tmp) b
SET
a.columnName = <VALUE>
WHERE
b.rowId = <rowNumber> AND
a.id = b.id;
NOTE The id column must be a unique one, you can use the primary key of that table...
SQLFIDDLE

Categories