I have a table:
id, affiliate
Each time somebody clicks a link, a new row is inserted,
ID being the ID of the page, and affiliate being the ID of the affiliate.
For example:
Page ID: 9 Affiliate ID: 1
Page ID: 9 Affiliate ID: 2
Page ID: 9 Affiliate ID: 3
I only have 3 affiliates.
I want to select this information, and group them by affiliate, for the ID.
I have tried this query:
SELECT COUNT(*) FROM table
WHERE id = '9' GROUP BY
affiliate
It works fine when I do it in php my admin, how do I get the info in PHP?
I have tried:
$q = mysql_query("SELECT COUNT(*) FROM
table WHERE id = '" . $id . "'
GROUP BY affiliate");
$r = mysql_fetch_array($q);
When trying to print the data onto the page, I am only getting one result.
Do I need to use a foreach/while loop to get all 3? How would I go about doing this?
Thank you!
You should do mysql_fetch_array() (or mysql_fetch_assoc()) in a loop:
while ($row = mysql_fetch_assoc($q)) {
echo $row["id"];
echo $row["affiliate"];
}
UPDATE (in accordance with comment):
If you ALWAYS have 3 rows in your result, probably mysql_result() function would be helpful:
$firstAffiliate = mysql_result($q, 0, "affiliate");
$secondAffiliate = mysql_result($q, 1, "affiliate");
$thirdAffiliate = mysql_result($q, 2, "affiliate");
BTW, be careful and check, whether query actually returns 3 results.
Loop like this:
while($row = mysql_fetch_array($q)) {
print_r($row);
}
If you just want to get list of Affiliate ID, you can consider this query
select group_concat(affiliate)
from table
where id=9;
The above will return a comma separate value like 1,2,3 in single row
So, you can then in PHP explode using ,, and the size of the exploded array is the same as count(*)
you can use a variable to hold state inside the actual mysql statement itself. Try the following:
affiliates:
page_id
afil_id
set #page_id=0;
select page_id, if(#page_id <> page_id, count(*), 0), #page_id:=page_id from clicks group by page_id;
Hope that helps
Related
By the way, before it is mentioned, I am well aware I should be using mysqli. Thanks in advance.
This is my code:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a 'lookup' table and has two columns:
userid and listingid
It has a many to many relationship. In other words, there could be one userid attached (associated) to multiple listingids and thus having multiple rows in that table.
e.g.
userid|listingid
1|1
1|2
1|3
2|1
etc
To keep things simple: What I want to do is check the following:
$a5['listingid'] == $_GET['id']
And if it is True I will display information and if it is False the information will not be displayed.
So on the page mywebsite.com there will be an id as so, mywebsite.com?id=[id here]. I am trying to see if the user $_SESSION[UserID] has an entry in userlisting table that matches the id of the page (well, it is a property website and the id is that of the property listing).
At the moment the code I have above just searches/checks for the first row for that userid only. In the example I gave above that would be listingid ='1' It is not seeing that row 2 and 3 also have entries in them too, listingid = '2' and '3' respectively. So on mywebsite.com?id=1 it is true, but on ?id=2 and id=3 it is coming up false, but userid = 1 has three rows with entries 1, 2 and 3.
I have been trying to find a solution for a while and I am starting to feel frustrated now. I would much appreciate it if someone could come up with a quick solution for me.
You can check both on SQL with some clause like
WHERE userid=XX AND listingid=XX
And remember to escape the get parameter ;)
PS: You can use too a while for iterate the mysql_fetch_row and search if anyone is correct. Something like:
$correct_check = false;
while($a5 = mysql_fetch_array($r5)) {
if($a5['listingid'] == $_GET['id']) $correct_check = true;
}
if($correct_check) ....
else ....
Try something like this
$page_id = $_GET['id'];
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]' and listingid = '$page_id' ";
$res = mysql_qury($result);
$num_rows = $mysql_num_rows($res);
if($num_rows > 0)
//your ok code
else
//fail message
I am looking for a way to increment and decrement by a step of three records in a table and return them.
Say ID '4' is currently active. I want to get the next 3 and the previous 3 records with IDs and category of 3.2.1 and 5.6.7 (via incrementing and decrementing).
So far I have:
$stmt = $db->query("SELECT id, category FROM test");
$stmt->execute();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$current = $results['id'];
$category = $results['category'];
$next = array(array(
'slide_no' => $current,
'category' => $category
));
}
print_r($next);
Using this, I am getting back every row in the table.
I'm getting confused how to increment and decrement the records by a step of 3 and make sure that the category will also increment accordingly.
Thank you very much.
You will need to create a string with the 6 ids that you need.
So if CatID was 4 you would want
$selectIDs = '1, 2, 3, 4, 5, 6, 7";
Then when you perform your SQl you would use
"SELECT id, category FROM test WHERE id IN (" . $selectIDs ."')";
If I understand your question correctly, you want to paginate the displayed data. You need to use the MySQL LIMIT clause.
You'll need to adjust your query, using values generated from your code. See an example below:
$stmt = $db->query("SELECT id, category FROM test LIMIT ?, 3");
#you'll supply the ? parameter depending on your current start index
MySQL Limit clause Tutorial
You can use the => and <= operators.
First store the id in a variable:
$intId = 4
Then add and decrement 3
$intAdd = $intId + 3
$intDecr = $intId -3
Then setup your sql string
$stmt = $db->query('SELECT id, category FROM test where id =>'. $intDecr.' and <= '.$intAdd. ');
I created a PHP file to populate a page, using AJAX, but I can't find a solution to my problem.
Here's my PHP and its Outputs:
$result = mysql_query("SELECT id, product, picture FROM table1 ORDER BY id DESC");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;
echo $output;
This will print:
[{"id":"5","product":"product5","picture":"picture5.jpg"},
{"id":"4","product":"product4","picture":"picture4.jpg"},
{"id":"3","product":"product3","picture":"picture3.jpg"},
{"id":"2","product":"product2","picture":"picture2.jpg"},
{"id":"1","product":"product1","picture":"picture1.jpg"}]
I want to add the field "In_Stock" on this Output using a another query to output something like this:
[{"id":"5","product":"product5","picture":"picture5.jpg","in_stock":"yes"},
{"id":"4","product":"product4","picture":"picture4.jpg","in_stock":"no"},
{"id":"3","product":"product3","picture":"picture3.jpg","in_stock":"yes"},
{"id":"2","product":"product2","picture":"picture2.jpg","in_stock":"yes"},
{"id":"1","product":"product1","picture":"picture1.jpg","in_stock":"no"}]
My question is: Its possible to use the value of the array (Inside the first While) to do a search in another table, add this value to products array and keep the same "layout" on the output above?
EDIT:
These are my tables:
TABLE1
id
product
picture
And the second one
TABLE2
id
user
product_id
in_stock
The same product may have different stocks depending on the User...
Yes, you could do another query, but it probably makes more sense to just alter the first query to include all the data you need, which would look something like this:
mysql_query("SELECT table1.id, table1.product, table1.picture, table2.in_stock
FROM table1
LEFT JOIN table2 ON (table1.id = table2.product_id
AND table2.user = " . intval($_SESSION['user']) . ")
ORDER BY table1.id DESC");
Edit: Added in the user from session per your comment. I used intval because I am assuming you are using an integer for the id of the user, and I don't know how the $_SESSION value got set - if it is from user input then it should be escaped.
As a side note, mysql_query is deprecated, you should look into mysqli and prepared statements.
How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.
i have a fetch row query that returns
10 9 8 7 6 5 4 3 2 1
however, i only want to return the last value, which is "1" in this case.
i tried to do echo row[0][9] but it doesn't work.
how do i get the last value?
you can use the end() function
$row = array(10, 9, 8, 7);
echo end($row); // displays 7
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Take a look # this example. Copied from here. You should be able to achieve what you wanted by taking a look at the above example.
If you know what the column index is, you are good to go. But if you ALWAYS want the last column take a look at the mysql_num_fields function.
Try echo explode(' ', $row[0])[9]
Been a while since I've done PHP though, YMMV.
you must sort your table by DESC keyword .
I'd do it all on MySQL side, so you don't split the logic between PHP and MySQL too much (if that's applicable in this case) and use query with LIMIT 1 and ORDER BY DESC (or ASC, depending on your table).
You only want the 10th last row that was added to the table? That would be the 10th id in the list if you sort by id descending. If that's what you want, you also could tell MySQL to return exactly that row. The query gets a bit more complicated though:
SELECT t1.*
FROM table t1
INNER JOIN (
SELECT id
FROM table
ORDER BY id DESC
LIMIT 10
) t2 ON t1.id = t2.id
ORDER BY t1.id ASC
LIMIT 1
Here's my code.
$query="SELECT blog_id FROM myblogs_view where blog_id<'$id' ORDER BY blog_id DESC LIMIT 10";
$result=mysql_query($query);
while($row=mysql_fetch_row($result) or die(mysql_error())) {
echo $row;
}
This returns the values in one row. how do i access the value in the last row only?