I am currently using PHP and MYSQL to show some results from my database, this all works fine, but I want to show an advert every five search results.
At the moment the results are just pulled from the database using the
while($row = mysql_fetch_array($result))
But i am not sure of the best way to count every five results, i did consider doing this using an id, but because the results are filtered they would not necessarily be in sequence and so i was hoping somebody could give me a nudge in the right direction.
$i=0;
while($row = mysql_fetch_array($result)){
$i++;
// show your mysql data here
if($i%5==0){
// show your ad here
}
}
TIP: depending on how big your SQL result is and how exactly you are echoing it, you might probably save some mem/time by using mysql_fetch_assoc() instead of mysql_fetch_array(), but YMMV
Related
I have 18 rows in one of my tables with several columns. I would like to extract the data from several different non-sequential rows and echo them individually on different parts of my page.
For example, let's say I wanted to pick records 5, 9 and 13 from column_1 and echo them to the page in different places. How would I accomplish this? Would I need to perform one query each to retrieve these unique fields? Here is my code so far:
// $database connect code, blah blah...
$sql = "SELECT page_id FROM pages WHERE (not sure if something should go here)";
$query = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($query)){
maybe some code here, not sure...
};
Doing so with ALL of the records in a specific column is easy using a while loop, but that's not what I'm after. I thought there may have been a way to cherry pick the specific row with an associative array like $fetchRow['row']['row_number'], but that doesn't appear to work. Performing one query for each unique instance seems awfully inefficient.
I'm familiar with how to retrieve things from the database and display them on the page. I'm intermediate level, but this has gotten me stumped.
Any ideas?
Thanks.
You'll need an IN clause.
$sql = "SELECT page_id FROM pages WHERE column_1 IN (5, 9, 13)";
Or if you'd rather do it with a PHP array, something like this:
$cols = array(5,9,13);
$in_cols = implode(',', $cols);
$sql = "SELECT page_id FROM pages WHERE column_1 IN ({$in_cols}})";
If you're going to use #2, make sure you properly sanitize/prepare the statement before executing it.
I think what you're looking for is data_seek
However, since you only have 18 rows... I would store all the result set in an array and use this array to echo the rows elements I want on the page. That way you do not have the overhead of typing the supplementary code (the best code is no code) and having to retrieve the specific rows you want. Furthermore, would you ever want to retrieve other records, there would be no need to modify your query.
Im following a video tutorial on mysql and php, and a certain line of code has me a bit confused:
<?php
$result = mysql_query("SELECT * FROM subjects", $connection);
if(!$result){
die("Database query failed: " .mysql_error());
}
while($row = mysql_fetch_array($result)){
echo $row["Menu_Name"]." ".$row["position"]."<br/>";
}
?>
I want to really understand what this code is doing, so let me see if i got it straight. Basically, what it does on my screen is return the various items store in my table subjects and displays them in their position. It does this by returning them in two arrays, one is the [menu-name] which stores the text for each item and the other is [position] which stores the order in which they come out. So, my while loop goes through this array and outputs. But that's what I dont get. What does $row do and how does it manage to go though and loop through. I may be way off here and was hoping someone could shed some light on this.
mysql_query sends a MySQL query. mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified. mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
One last thing if you want to know what's happening with a function try referring the documentation. It helps most of the time.
According to the question you have asked I guess you should go through the basic MYSQL and PHP lessons.
Those are not two arrays. That is one array which is Multi dimensional
while($row = mysql_fetch_array($result)){
When you run that line of code then it grabs one complete row from the list of your results and assigns it to an array named $row. You can then give your Index names to get data from it just like you wrote
$row["Menu_Name"]
So Menu_Name is an index of an array $row containing some value which came from your database. Since this statement is present in a loop, it will loop through all the rows of your returned result and do the same for each of them
this line is retrieving table records, line by line. This is actually an array representing a table record.
$row = mysql_fetch_array($result)
Now, this array in indexed by the table field names. Because your query is 'select *', it means that its retrieving all fields.
So,
$row["Menu_Name"]
has the value of the field 'Menu_Name' of the table 'subjects', for the current row.
SEE tutorial example http://www.devmanuals.com/tutorials/php/phpmysql/php-mysql-fetch-array-example.html.It may clear your doubt
I run a query and get a result set. I need to get the nth record from this result set. Any ideas how I can do this?
I cannot select the nth record from the database directly coz I need to filter it and don't know how many records there are in the result set. So I cannot be certain which number to pass to the mysql_result method i.e.
Based on certain conditions, get a few rows from a table
From these rows, select the nth row (the number n is not fixed. It depends on the number of records returned)
The basic idea is to get all results based on a set condition and get a random result from these.
Any ideas? Thanks.
Your question seems unclear. However here's a guess:
You want to select the record in the middle:
$count = mysql_num_rows($result);
$middle_name = mysql_result($result, intval($count/2), 'name');
Besides that, you can also do that if you have really less records:
$rs = array();
while ($row = mysql_fetch_assoc($result)){
$rs[] = $row;
}
and then you can use $rs[N-1] to reach Nth record.
Read mysql_data_seek from PHP Manual if you will fetch just one record.
The basic idea is to get all results based on a set condition and get a random result from these.
SELECT ... ORDER BY RAND() LIMIT 1
I know this is not best practice, but as the given information is rather sparse, this could be starting point for further reading. And to be honest, in an small enough application, this is often the easiest solution.
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.
I have the following code:
<?php
$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);
$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);
echo "<b>Quests Available for ".$npcname."</b><br>";
while($row=mysql_fetch_array($listquests2)) {
echo $row['name'];
}
?>
To go with this I have some tables whcih look like this:
npcs
name|location|npcid
quests
name|qid|npcid
So a quest is associated to a NPC via the npcid field.
I have one entry in each table.
Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1
As you can see the quest and Bob both share the npcid of 1.
In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.
If I put the code:
$listquests3['name'];
Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.
If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.
Thank You.
It may be a good idea to print out the SQL and run this against your database to see what results you get.
Looking at this it looks like there may only be one result which is fetched in the
$listquests3=mysql_fetch_array($listquests2);
line. Since there are no more results there is nothing to loop over.
The results are already fetched, since there is only one rule and you fetched it in $listquests3 :). It will work if you remove that line I think.
You need to do a INNER JOIN or a LEFT JOIN. Yes after carefully seeing the question again, I found that when doing the "mysql_fetch_array()" code for the first time (just before the "while" loop), the value of the variable "$listquests2" gets lost. So the "while" loop does nothing fruitful.
You must remove this single line for variable "$listquests3".
You only have one row, and you fetched that row when you called mysql_fetch_array the first time. When you call it the second time, there are no more rows to fetch in the result set, the function returns false and your loop exits.
This statement: "$listquests3=mysql_fetch_array($listquests2);" already fetches the first. Sicne you have only one, there's nothing more to fetch, so the next call to mysql_fetch_array will return nothing.
That should fix it, but for your own 'experience', this might be a good moment to start learning about MySQL joins (LEFT JOIN in particular). You can easily find a lot about it on the internet!
I'm learning currently php/mysql and I'm confused about this bit.
After some heads scratching I have figured out that mysql_fetch_array remembers which row it last accessed and accesses the next one. (I was originally trying to work out how the code was communicating this to it in example code)
so for database:
parent | job
-------+-------------
mom | receptionist
-------+-------------
dad | taxi driver
the code
mysql_fetch_array($result)[job]
returns 'receptionist' the first time and 'taxi driver' the second.
Where/how is it keeping track of this?
What happens if I don't want to access them in order?
thanks
internal implementation in PHP. Don't try to figure it out ;)
if you want a different order, then specify it in your database query.
Where/how is it keeping track of this?
The mySQL server has an internal result pointer. In some databases / wrappers / libraries you can rewind that pointer, but as far as I know, this is not possible in the mysql_* library of functions.
What happens if I don't want to access them in order?
You have to access them in some order. The only alternative to that is to fetch all rows into an array: Then you can access each row randomly.
If you want to change the order of records, do that in the query using the ORDER clause.
Some database wrappers like PDO have a fetchAll() method that does exactly that. For large result sets, this can be memory intensive and break the script's memory limit, which is why it's usually not done this way.
There is another way to attack this question.
If you want to know how YOU TOO can make functions that do what this one does. Here is how:
<?php
function count_off()
{
static $count = 1;
echo $count++;
}
count_off();
count_off();
count_off();
count_off();
count_off();
?>
the above will output 12345
I should mention. You shouldn't do this without a very good reason. It is SUPER hard to trace when debugging.
If you want to access them in a different order, use an ORDER BY clause in your SQL to change the order that the results are retrieved from the database.
The result of mysql_fetch_array is always the next result/row of the query (first the first row off course)
Intern it will keep a pointer how for it has fetched.
If you want to get them in an alternate order, you have to define it in the query.
Like said the result will always be in the order specified by the query (implicit or explicit)
If you wrote typical looking code like this:
$result = mysql_query("SELECT parent, job FROM table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['parent'] . ' - ' . $row['job'];
}
Each time mysql_fetch_array() is called, if there is another row in the result, it will return the row as an associative array into the $row variable. Otherwise, it will return false, and the execution of the while loop will end.
Also, because you didn't specify an ORDER BY clause, it defaults to returning rows in the order they were inserted into the table.
The mysql_fetch_array() function grabs one row from the database, in the order that MySQL returns it from the query you gave.
To obtain all the rows, you can put the function in a loop.
while($row = mysql_fetch_array($result)) {
echo $row["job"];
}
This will output:
receptionist
taxi driver
You can change the order by using the sql term order by, which can alphabetically or numerically order your results by a certain column
select * from parent order by job
The above query will order the results alphabetically by the parent job field (results closer to A will come first in the mysql_fetch_*