A php custom function returns record set from a mysql query.
I need to populate a two column table having equal quantity or balanced between two.
I know we can split by number of columns the row count then use a loop to populate each td accordingly.
Any suggestions or most practical way to display record sets onto tables organized according to their sizes?
Not using templates at this time.
Basically need to control the TD tag from been echo or not and filled.
Sample Code:
$col_num = 2; //Number of colums to parse data onto.
$count_r = mysql_num_rows($result)/$col_num;
echo '<table style="width:400px;border:3px solid green;"><tr><td>';
$ui=1;
while($row = mysql_fetch_array($result))
{
if($ui<$count_r)
{
echo '<input disabled type="checkbox" value="$row[id]"'; $this->ischecked($uid,$row[id]); echo "/>".$row['name'].'<br>'."\r\n";
}
$ui++;
}
//FIRST COLUMN SET
echo '</td>';
echo '<td>';
//SECOND COLUMN SET
echo '</td></tr></table>';
If you don't mind about the order of your records you could simply do (assuming you've got your results in an array called $result) the following:
...
echo "<table>";
for($i=0;$i<count($result);$i+=2):
echo "<tr>";
echo "<td>{$result[$i]['field']}</td>";
echo "<td>{$result[$i+1]['field']}</td>";
echo "</tr>";
endfor;
echo "</table>";
I don't know if it's the best way of doing this but it's the way I'd do it in your case. Keep in mind that I'm not checking if there are any actual results, we are assuming that it's the case. To check if $results is set you could use an if statement checking it's count number for example.
Note
Replace for($i=0;$i<count($result);$i+=2): with for($i=0;$i<count($result);$i+=2){ and endfor; with } for a traditionally formatted code.
I'd recommend using an unordered list -- <ul>, and apply the CSS float attribute to its list items (<li>). That way, you won't have to worry about counting the number of records.
Just output each record in a <li>, and set them all to float: left;.
Then constrain the height of the <ul> so it will be short enough to force the extra <li>s to float to a new column.
As #Steve pointed out, you'll also need to set the <li> width to be constant so the columns will be consistent. And make the width of your <ul> more than twice and less than three times as big as the <li> width.
A basic way to do that would be to call mysql_num_rows() on your query. Multiply the result by the height of each <li>, then divide by two, and that will be the height of your <ul>. That will make each column of equal height.
You could also do it with <div>s (one <div> for each item, all wrapped in a single global <div>).
But using a list is the preferred way of displaying a list of information in HTML (unless the information is tabular in nature and requires multiple columns per field, which yours isn't and doesn't).
If you need more detailed help, there's a great Opera Web Standards article on this.
Related
I have two mysql tables. I want to get the data from these tables and show it in a loop. The data is totally unrelated to each other and should stay that way. I just need to show data from these two different tables in the same place.
I tried the mysqli_multi_query, but I couldn't show the results from an individual column like I can with a normal query.
For each of these two tables, I need 2 SELECT statements with two WHERE clauses. Does anyone know how to do this?
I've tried all different ways of trying to get the info from both tables and just show them in one loop. I've tried mysqli_multi_query, but don't know how to save specific column results in a variable.
$sql = "SELECT *
FROM misc
WHERE height LIKE '$height_input'
SELECT *
FROM bolts
WHERE name LIKE '$bolt_name_input'
;
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$height_row = $row['height'];
$bolt_name_input = $row['name'];
?>
Height Row: <?php echo $height_row; ?>m<br />
bolt Name: <?php echo $bolt_name_input; ?><br />
} //while
My error message is generally "Trying to get property 'num_rows' of non-object".
Yes everyone, I have taught myself PHP and MySQL through online tutorials and have not had a lot of experience with them yet. I apologise, I am still getting the hang of this.
I have just worked out now by trial and error that I can show information from a table outside of the while loop. I had no idea I could do this! Which changes everything. So I can select information from various database tables using different SELECT statements and then echo them all into one place in my HTML table underneath it on my web page. The results don't have to be shown in the while loop, they can be outside it.
So my structure now looks like this basically:
SELECT from table 1 column 1 WHERE (form input value)
num rows
while loop
$height = $row_height['height'];
end num rows
end while loop
SELECT from table 2 column 1 WHERE (form input value)
num rows
while loop
$bolts = $row_bolts['bolts'];
end num rows
end while loop
<table>
<tr>
<td>echo $height</td>
<td>echo $bolts</td>
</tr>
</table>
So, this is working for me to retrieve multiple results from my different tables. I have to change the variable names of the sql statement each time, I guess I could do it with a function so i can repeat it and make it look neater, but this is working for me this way. So, with bolts I am using the variable names $sql_bolts, $result_bolts and $row_bolts and with height I am using variable names $sql_height, $result_height and $row_height and so on.
$bolts_input = $_POST['bolts'];
$sql_bolts = "
SELECT *
FROM bolts
WHERE name LIKE '$bolts_input'
;";
$result_bolts = $conn->query($sql_bolts);
if ($result_bolts->num_rows > 0) {
// output data of each row
while($row_bolts = $result_bolts->fetch_assoc()) {
$bolts = $row_bolts['name'];
} //bolts while
} // bolts num rows
I am not using mysql, but mysqli. I did a whole bunch of tutorials on PDO and how to connect to the database and retrieve information and just couldn't figure out how to show values from a row like I can with the above. It's frustrating because I want to use the latest methods, but I can't find how to online that makes sense to me.
Thank you for eveyone's comments so far.
you see, I have these variables that are set within a While, I'm using MySQL also, What I want to do is to sort of "Group" those variables into one, and then the rest of the variables that are not repeated, i want to assign them "Display:none" So , look at this image:
Now, as you can see there is two duplicate dates, but the values are different, so in this case (Take in mind that I only want to group these "Recibos" but dont worry about it) you can see in the first row it has a different date, and has no repeated dates, while the last two of "Recibos" is sort of duplicated
Basically what I want to do is to group the two last "Recibos" (The duplicate dates), only one of the same date has to appear, and the rest of them, are gonna be shown when the TR is hover
Though , I only want a simple version of what I want, it can be some sort of testing, as you can see in this image, i've been trying for weeks and still didnt get anything, I hope you can help me! thanks in advance
I have made this code, which is the one in the image above:
Inside the while:
$acumulado-=$monto;
if(($fila>=$mostrar_de_aca_en_adelante && $detalles=='minimo') || ($detalles=='maximos')){
$conteo++;
$string_fecha[$conteo] = $fecha_operacion;
$string_fecha_tmp[$conteo] = $fecha_operacion;
$recibo_id_cliente[$conteo]=$id_cliente;
$recibo_monto[$conteo]=$monto;
$recibo_saldo_total[$conteo]=$saldo_total;
$recibo_detalle_movimiento[$conteo]=$datos_detalles['detalle_movimiento'];
$recibo_recibo[$conteo]=$recibo[0];
$recibo_verificado[$conteo]=$datos_detalles['verificado'];
$recibo_acumulado[$conteo]=$acumulado;
$label = $monto;
}
Outside the while:
echo "<br><br><br>";
for($i = 1; $i <= $conteo; $i++){
if($string_fecha[$i] == $string_fecha_tmp[($i + 1)]){
$label += $recibo_monto[$i];
$string_imprime_tmp .= "<br>[Repetido]".$string_fecha[$i]."(".$label.")";
}
}
echo $string_imprime_tmp;
var_dump($string_fecha);
By the way: I know this can be done in MySQL, but it can only be done in php i'm limited to php.
I'm working in the IT department of my company and it is my responsibility to send daily reports of the calls registered in the Call Center department. I'm new with MySQL, PHP or HTML and I'm already facing my first problems.
My objective is to run some queries in PHP and then output them in a HTML table cell. Let me be more specific. I have access to a telephone record database and I need to count the number of total calls and lost calls of every branch daily. Right now I just run 2 queries in MySQL and then copy-paste them in a .xls table.
I have the right queries, I get the right result in mysql, even in PHP I get the result posted on the webpage (kind of), but I don't know how to create a table, or how to input the result of a query into a specific cell of the table.
Here's what I've got so far:
<?php
$conn=#mysql_connect('host', 'username', 'password', 'asteriskcdrdb.cdr');
echo ('total calls ROPCW: ');
$result=mysql_query('select count(*) from asteriskcdrdb.cdr where calldate like "2016-04-11%" and dst="020" and disposition="ANSWERED" and duration > "10" ');
echo mysql_result($result, 0);
mysql_close($conn);
?>
This code will post on my page the count of total calls made on 4.11.2016 like this:
total calls ROPCW: 369
My objective is to create a table like this:
So the result of that query I mentioned above would go on the ROPCW->Total cell (where is 305) on the left side, on the right side are the monthly reports so far.
You can work out one big query or use a view to gather the data you need from a single source. Other suggestion would be, looping through all your branches and gather all the data you need, to build an associative array indexed similar to this:
$records[branch] = [date => [total => x, lost => y], mtd => [total => X, lost => Y]];
Then just do a:
foreach ($records as $branch => $record)
{
echo string to build table row
}
I suggest use mysql_fetch_object or mysql_fetch_assoc functions instead of mysql_result. Basically because those functions fetch an entire row instead of one single cell value. For your example query works fine because your aggregate function returns only one cell and row. But for your desired output won't work.
Keep in mind that you can inject HTML code within PHP and vice versa. Just do something like:
The idea would be run a select * from yourTable;
Then,
$result = mysql_query($sql);
echo "<table>\n";
echo "<tr><th>Branch</th></tr>\n";
while ($callRecord = mysql_fetch_object($result)) {
echo "<tr><td>{$callRecord->branch}</td></tr>\n";
}
echo "</tr>\n";
echo "</table>\n";
That should output a list of all tour branches. this is a guideline.
Hope this helps!!
You can go to www.php.net and choose between mysql_fetch functions which one will work better for you.
My first post, tried to be as thorough as possible, apologies in advance if I've gotten something wrong. I'm pretty novice with PHP/SQL as well so please be patient with me. I've found a couple of similar questions about loops within loops but I'm not sure the solutions apply in my case.
I have two tables, tws_workshopNames and tws_workshops. The primary key from tws_workshopNames is used as a foreign key in tws_workshops to relate the two tables. The reason I've split this into two tables is there are many cases where the same workshop name/price/description is offered on multiple dates/times.
Can't submit a screenshot but here's a simplified outline of the table design in SQL Server:
tws_workshopNames:
workshopNameID (pri)
description
price
etc.
tws_workshops:
workshopID (pri)
workshopNameID (foreign)
date
time
etc.
What I want to happen is basically this:
query tws_workshopNames table and display workshopName/price/description/etc.
for each workshopName go through the tws_workshops table and display all records that have the same workshopNameID
In other words, go through tws_workshopNames and display the first workshopName, then go through tws_workshops and display all records that are related to that workshopName, then go to next workshopName in tws_workshopNames, display all records related to that workshopName etc.
I'm able to achieve the desired result by using a while loop within a while loop wherein the outer loop does a call to tws_workshopNames and the nested loop does a call to the tws_workshops table. However I've been reading a lot about this and it's clear this is not a good approach as it results in a lot of calls to the db, but I'm having a hard time understanding any alternatives.
Desired output:
Workshop 1
price
description
date (of workshop 1)
time (of workshop 1)
...
Workshop 2
price
description
first date (of workshop 2)
first time (of workshop 2)
second date (of workshop 2)
second time (of workshop 2)
third date (of workshop 2)
third time (of workshop 2)
...
Workshop 3
price
description
date (of workshop 3)
time (of workshop 3)
...
etc.
Here is the current code that works with nested while loops:
<?php
// query workshopNames table, what types of workshops are available?
$query = mssql_init("tws_sp_workshopNames", $g_dbc);
// pull up result
$result = mssql_execute($query);
$numRows = mssql_num_rows($result);
while($row = mssql_fetch_array($result)) {
echo "<div style=\"...\">
<span class=\"sectionHeader\">" . $row['workshopName'] . "</span><br />
<span class=\"bodyText\"><strong>" . $row['price'] . "</strong></span><br />
<span class=\"bodyText\">" . $row['description'] . "</span>";
$workshopNameID = $row['workshopNameID'];
// query workshops table, what are the dates/times for each individual workshop?
$query2 = mssql_init("tws_sp_workshops", $g_dbc);
mssql_bind($query2, "#workshopNameID", $workshopNameID, SQLVARCHAR);
//pull up result
$result2 = mssql_execute($query2);
$numRows2 = mssql_num_rows($result2);
while($row2 = mssql_fetch_array($result2)) {
echo $row2[date] . " ";
echo $row2[time] . "<br />";
};
echo "</div><br />";
};
?>
The stored procedures are very simple:
tws_sp_workshopNames = "SELECT workshopNameID, workshopName, description, location, price FROM tws_workshopNames"
tws_sp_workshops = "SELECT date, time, maxTeachers, maxStudents, teachersEnrolled, studentsEnrolled FROM tws_workshops WHERE workshopNameID=#workshopNameID"
Hope that's all relatively clear, all I'm really looking for is a better way to get the same result, i.e. a solution that does not involve a db call within the loops.
Thanks in advance for any help, been a few days straight banging my head against this one...
You are correct to avoid usage of looping queries in this case (since the desired result can be achieved with just a simple JOIN in one query).
I would avoid using GROUP_CONCAT() as well because there is a character limit (by default, you can change it), plus you have to parse the data it outputs, which is kind of a pain. I would just get all the data you need by joining and get every row. Then load the data into arrays using the workshop ID as the key but leave the array open to append each of your time data as a new array:
$workshops[$workshop_name][] = $timesArray;
Then on your output you can loop, but you don't have to hit the database on each call:
foreach ($workshops as $workshop_name => $times)
{
echo $workshop_name;
foreach ($times as $time)
{
echo $time;
}
echo "<br>";
}
This is not the exact code, and as you've pointed out in your question, you want to keep/display some other information about the workshops - just play around with the array structure until you get all the data you need in a hierarchy. You can use something like http://kevin.vanzonneveld.net/techblog/article/convert_anything_to_tree_structures_in_php/ if you are trying to build a deep tree structure, but I think that's overkill for this example.
Since this is what I would call an "Intermediate Level" question, I think you should try to work through it (THIS is what makes you a good programmer, not copy/paste) using my suggestions. If you get stuck, comment and I'll help you further.
I don't see anything wrong with the way you're doing things. I suppose you could concatenate the result and then manipulate the output in your application using one query. Your query might looks something like
SELECT
n.workshopNameId,
n.price,
n.description,
GROUP_CONCAT(w.date) as dates,
GROUP_CONCAT(w.time) as times
FROM tws_workshopNames n
INNER JOIN tws_workshops w USING(workshopNameID)
GROUP BY n.workshopNameID
I want to code a script that will echo an amount of images based on the mysql_num_rows(); function.
Like, I'm storing 3 in a row. Then I'll create:
$images = mysql_num_rows($count);
Then I would like it to echo 3 images.
Is this possible?
If you don't get the question or want me to rewrite it, please just tell me.
Then i think, all you need to do is fetch the rating (i.e. a number) from the database and just use that number directly to display the number of stars. Coz mysql_rows_count would give you the total number of records in a result set which is returned as a result of a select query on multiple columns, but in your case you only need to access one column which would contain the rating and another column which would probably contain user id or some sort of key to associate the ratings with. The result set can be fetched as an associative array which can then be used by indices to fetch the right column. Have a look at this: PHP-mysql_fetch_array() .
EDIT: just to sum up (not the actual syntax) :
$array = mysql_fetch_array(<your select query fetching only the needed columns>);
$images = $array[0] // assuming the rating number is at the 0th index
//image display code, do your stuff
So here is what I did:
I had the numbers from 1-5 in my database in a row called 'rating'. Now when I picked this out of the database I stuffed the number (1-5) into a variable called '$starRating'.
for($i=1;$i<=$starRating;$i++){
echo "<span class='star'><span class='starText'>$i</span></span>";
}
Then I created a class called star and starText:
.star{
width:18px;
height:18px;
background:url('../images/design/smallImg/star.png') no-repeat;
text-align:center;
float:right;
margin-top:2px;
}
/* star content */
.starText{
display:none;
}
.starText is made to hide the text that would've been from the for() loop.
* I don't know if you can avoid the text another way around *
This works for me perfectly.
I wrote this to help people searching for an easy solution to this.