Selecting several nonsequential rows in table - php

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.

Related

Codeigniter check if one columns items present in another column

I have been trying to figure out how to check if any of one column's items present in another column in Codeigniter....
I have Bike,Car,Bus in a column(Vehicles) in a table1...
I also have Bus,Helicopter,Ship,Car in a column(Interested) in table2..
How to check if any of table2 interested column's items present in table1 vehicles column...
I tried like this...
$query = $this->db->get('table2');
foreach($query->result() as $row)
{
$a = explode(',', $row->interested);
$this->db->where_in('Vehicles', $a);
$query = $this->db->get('table1');
foreach($query->result() as $row2)
{
echo $row2->ID;
}
}
Could it be done ?? Please Help me... Thanks in advance....
It is very hard to help you without seeing the tables and how you are relating one to the other (such as user_id).
What you should do is two queries. One query to get the data from table 1 of the vehicles you are interested in. Then run through the result set and create a simple array of those vehicles in php. Then do a second query using where_in to select all the rows that are in the chosen vehicles array.
Your method is bad because the number of db queries depends on the size of the result set of your first query. You might find your code trying to do hundreds of database queries.
If you show a diagram of your tables, I could write some example code for you.
Here are the docs for where_in: https://www.codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where_in

Dynamic Table Rows with PHPWord

I am hoping someone can help me because I am attempting to do something that is beyond my limits, I don't even know if a function exists for this within PHP or MySQL so my search on google hasn't been very productive.
I am using PHPWord with my PHP/MySql Project, the intention is that I want to create a word document based on a template.
I have used this guide which is also on stack exchange.
However this approach requires that the number of rows and the values are hard coded, i.e. in his example he has used cloneRow('first_name', 3), which then clones the table to have 3 rows, and then goes on to manually define the tags, i.e.
$doc->setValue('first_name#1', 'Jeroen');
$doc->setValue('last_name#1', 'Moors');
$doc->setValue('first_name#2', 'John');
I am trying to make this dynamic, in my instance I am trying to make a timetable, and one of the child tables is exactly that, so the query I have looks up how many entries there are and then collects a count of them, this $count is then used to dynamically create the correct number of rows. This is the count I am using:
$rs10 = CustomQuery("select count(*) as count FROM auditplanevents where AuditModuleFk='" . $result["AuditModulePk"]."'");
$data10 = db_fetch_array($rs10);
$Count = $data10["count"];
I then use this $document->cloneRow('date', $Count); to executive the clonerow function, which works great and my document now looks something like this.
So, so far so good.
What I now want is for a way to then append each row value of the query into the document, so rather than manually setting the tag value i.e. $doc->setValue('first_name#1', 'Jeroen'); I could use something like $doc->setValue('first_name#1', '$name from row 1'); I suspect this will involve a foreach query but not too sure.
I hope the above makes sense, but please feel free to ask me for anything else and become my personal hero. Thanks
Update: Just for sake of clarity, what I would like is for the output to look something like this:
In my example are 5 results and therefore 5 rows created, I want to set values in following way:
${$date1} = date column from query 1st row
${$date2} = date column from query 2nd row
${$date3} = date column from query 3rd row
${$date4} = date column from query 4th row
${$date5} = date column from query 5th row
I was able to sort this out by inserting the records from the query into a temp table, with an AI ID, then using:
//update timetable with events from temp table
$rs14 = CustomQuery("select * FROM tempauditplan where AuditModuleFk='" . $result["AuditModulePk"]."'");
while ($data14 = db_fetch_array($rs14))
{
$document->setValue('date#'.$data14["rowid"], date('d/m/y', strtotime($data14["date"])));
$document->setValue('time#'.$data14["rowid"], date('H:i', strtotime($data14["time"])));
$document->setValue('auditor#'.$data14["rowid"], $data14["auditor"]);
$document->setValue('area#'.$data14["rowid"], $data14["area"]);
$document->setValue('notes#'.$data14["rowid"], $data14["notes"]);
$document->setValue('contact#'.$data14["rowid"], $data14["contact"]);
}
The trick is to also have a function that truncates the table after use so can be used over again
Might not be the most efficient way, but it works!

PHP/MySQL: Massive SQL query or several smaller queries?

I have a database design here that looks this in simplified version:
Table building:
id
attribute1
attribute2
Data in there is like:
(1, 1, 1)
(2, 1, 2)
(3, 5, 4)
And the tables, attribute1_values and attribute2_values, structured as:
id
value
Which contains information like:
(1, "Textual description of option 1")
(2, "Textual description of option 2")
...
(6, "Textual description of option 6")
I am unsure whether this is the best setup or not, but it is done as such per requirements of my project manager. It definitely has some truth in it as you can modify the text easily now without messing op the id's.
However now I have come to a page where I need to list the attributes, so how do I go about there? I see two major options:
1) Make one big query which gathers all values from building and at the same time picks the correct textual representation from the attribute{x}_values table.
2) Make a small query that gathers all values from the building table. Then after that get the textual representation of each attribute one at a time.
What is the best option to pick? Is option 1 even faster as option 2 at all? If so, is it worth the extra trouble concerning maintenance?
Another suggestion would be to create a view on the server with only the data you need and query from that. That would keep the work on the server end, and you can pull just what you need each time.
If you have a small number of rows in attributes table, then I suggest to fetch them first, fetch all of them! store them into some array using id as index key in array.
Then you can proceed with building data, now you just have to use respective array to look for attribute value
I would recommend something in-between. Parse the result from the first table in php, and figure out how many attributes you need to select from each attribute[x]_values table.
You can then select attributes in bulk using one query per table, rather than one query per attribute, or one query per building.
Here is a PHP solution:
$query = "SELECT * FROM building";
$result = mysqli_query(connection,$query);
$query = "SELECT * FROM attribute1_values";
$result2 = mysqli_query(connection,$query);
$query = "SELECT * FROM attribute2_values";
$result3 = mysqli_query(connection,$query);
$n = mysqli_num_rows($result);
for($i = 1; $n <= $i; $i++) {
$row = mysqli_fetch_array($result);
mysqli_data_seek($result2,$row['attribute1']-1);
$row2 = mysqli_fetch_array($result2);
$row2['value'] //Use this as the value for attribute one of this object.
mysqli_data_seek($result3,$row['attribute2']-1);
$row3 = mysqli_fetch_array($result3);
$row3['value'] //Use this as the value for attribute one of this object.
}
Keep in mind that this solution requires that the tables attribute1_values and attribute2_values start at 1 and increase by 1 every single row.
Oracle / Postgres / MySql DBA here:
Running a query many times has quite a bit of overhead. There are multiple round trips to the db, and if it's on a remote server, this can add up. The DB will likely have to parse the same query multiple times in MySql which will be terribly inefficient if there are tons of rows. Now, one thing that your PHP method (multiple queries) has as an advantage is that it'll use less memory as it'll release the results as they're no longer needed (if you run the query as a nested loop that is, but if you query all the results up front, you'll have a lot of memory overhead, depending on the table sizes).
The optimal result would be to run it as 1 query, and fetch the results 1 at a time, displaying each one as needed and discarding it, which can reek havoc with MVC frameworks unless you're either comfortable running model code in your view, or run small view fragments.
Your question is very generic and i think that to get an answer you should give more hints to how this page will look like and how big the dataset is.
You will get all the buildings with theyr attributes or just one at time?
Cause your data structure look like very simple and anything more than a raspberrypi can handle it very good.
If you need one record at time you don't need any special technique, just JOIN the tables.
If you need to list all buildings and you want to save db time you have to measure your data.
If you have more attribute than buildings you have to choose one way, if you have 8 attributes and 2000 buildings you can think of caching attributes in an array with a select for each table and then just print them using the array. I don't think you will see any speed drop or improvement with so simple tables on a modern computer.
$att1[1]='description1'
$att1[2]='description2'
....
Never do one at a time queries, try to combine them into a single one.
MySQL will cache your query and it will run much faster. PhP loops are faster than doing many requests to the database.
The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again.
http://dev.mysql.com/doc/refman/5.1/en/query-cache.html

Select nth record from a SQL result set in php

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.

"how many search results from mysql" help

I got some help with gettin the number of rows returned from mysql, and it works fine...
BUT, how do I get the number of rows with a certain field value?
Do I have to make a new Mysql search query?
Here is the code where I query mysql and display in a table using fetch_array... Also, Im using mysql_num_rows to get number of rows.
So how do I get number of rows with certain field value also?
$qry_result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result))
Thanks for all help
OBSERVE: Im trying to avoid using another SELECT WHERE clause...
Is there a way to do what I want withouth another search?
In your query, you can use the where clause. (select * from table where column1 = 'value')
Another option would be to have a counter variable that you increment in your while loop:
$counter = 0;
while($row = mysql_fetch_array($qry_result))
{
if($row[0] == "value")
$counter++;
}
After you have this counter, reset the result set using mysql_data_seek($qry_result, 0); and then continue with your original while loop.
There are several ways to reach this, either run additional queries against MySQL or use programm logic to calculate what you need while iterating over the array.
Fetching the number of rows from MySQL is a task that has several solutions as well. You could blindly call SELECT count(*) FROM table WHERE foo = bar, or use the more advanced SQL_CALC_FOUND_ROWS variable of the database.
If you could explain yourself better, I would be glad to provide a good solution!
OBSERVE: Im trying to avoid using another SELECT WHERE clause... Is there a way to do what I want withouth another search?
I'm curious why you don't want to use another SELECT WHERE clause?
From what I interpret of your question, you are asking to have the number of rows of a given query AND, a count of unique variables?
ex:
NAME AGE
Joe 15
Simon 13
Simon 16
Joe 21
Mary 15
Joe 28
Your row count would be 6 and your count (that you are requesting) would be:
Joe x 3
Simon x 2
Mary x 1
If that is what you are asking, why not use 2 queries, 1 for your set of data, and another query where you GROUP BY 'name' and return only UNIQUE 'name' results? That would get you a count of your "certain fields".
Then again correct me if I miunderstood your question.

Categories