I have the following PHP code:
echo "var s1 = [";
$count = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0) echo ", ";
echo $row['OrdersBal'];
}
echo "];\n";
echo "var ticks = [";
$count2 = 0;
while($row2 = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count2++ > 0) echo ", ";
echo "'" . $row2['CardName'] . "'";
}
echo "];\n";
It's currently outputting:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = [];
But I want it to output:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = ['Parameter Technology', 'Earthshaker Corporation', 'Microchips', 'Mashina Corporation', 'SG Electronics'];
If I move the second while statement so that it occurs first then that statement will output correctly. This has lead me to believe that I can't execute two while statements in a row in this fashion, but I'm not sure what my alternatives are. Thanks for any help!
Use variables to store text during loop and then print them out:
$count = 0;
$orders = "";
$cardNames = "";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0)
{
$orders .= ", ";
$cardNames .= ", ";
}
$orders .= $row['OrdersBal'];
$cardNames .= $row['CardName'];
}
echo "var s1 = [" . $orders . "];\n";
echo "var ticks = [" . $cardNames . "];\n";
Related
I am trying to add a character before/after value in mysql query. but I can't make it work.
This is the part that doesn't work in my case:
$query = "select CONCAT ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
You can see the full code below. Any ideas why it doesn't work or can I get an alternative solution, please. thanks.
<div class="container">
<div class="left">
<?php
include ("etc/config.php");
$query = "select concat ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" size="44" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
?>
</div>
<div>
<?php
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
echo '</table>';
mysqli_close($link);
?>
</div>
</div>
For the 2nd half of your code, you can do this:
note you won't need to concat anything in your initial query
if(isset($_GET['mySelect'])) {
// configure every option here, if there's not pre/postfix, use a blank string
$prepostfixes = [
'DuRpt' => ['.', '.'],
'DaRpt' => ['', ''],
];
$myselect = $_GET['mySelect'];
if (!isset($prepostfixes[$myselect])) {
die ('Unknown Select'); // this will prevent sql injection
}
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
$prefix = $prepostfixes[$myselect][0];
$postfix = $prepostfixes[$myselect][1];
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $prefix . $row["mySelect"] . $postfix . "</td></tr>";
}
}
}
Just update your code and remove the duplicate of DuRpt from it.
$query = "select concat ('.', DuRpt) as DuRpt from DDtb order by DATE DESC";
I have the following working array of an array in PHP:
$explore1 = array
(
array("a.html", "A"),
array("b.html", "B"),
array("c","C")
);
$arrlength = count($explore1);
for($x = 0; $x < $arrlength; $x++) {
echo '<li>'.$explore1[$x][1].'</li>';
} }
I want to populate the explore1 array from SQL. If i simply change the code like below it has errors but I don't know what I'm suppose to do instead?
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$explore1 = array //IT DOESN'T LIKE THIS LINE
(
while($row = $result->fetch_assoc()) {
// BUILD SAME LINES AS ABOVE WITH ECHO
echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
}
);
Can anybody help?
Either you don't need $explore1 at all:
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
or if you need you can fetch_all():
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$explore1=$result->fetch_all(MYSQLI_ASSOC);
foreach($explore1 as $row ) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
Please learn some php basics.
Defining an array of arrays is something like:
$explore1 = array();
while($row = $result->fetch_assoc()) {
$explore1[] = array($row["url"], $row["name"]);
}
You must populate the array inside the loop:
while($row = $result->fetch_assoc()) {
$explore1[$row["url"]] = $row["name"];
}
I am building a dynamic table using php, pear HTML_Table, and sql.
My the first query pulls the information for the table headers, and then pear uses this to create the headers. The next query pulls the information from multiple tables to return the correct data sets. Next, I need to tie these data sets to the headers and display the results down each matching column. I am able to display all of the data, but not properly. Column 0 starts at row 1, and displays the current 4 test items, column 1 starts at row 5 and displays the current 2 test items, column 2 then starts at 7...How can I get the column count to reset to 0 after the previous column runs out of matching data? The other part of this problem is that I also need to apply rowSpans to the inserted data as this is a scheduling project. I have been at this for a week now and have been unable to find any relevant examples or suggestions. What am I missing, as I don't think this should be such a difficult task?
Code below.
<?php
session_start();
include_once("../php/functions.php");
include_once("HTML/TABLE.PHP");
$assetHead = headers('Assets', $_SESSION['deptID']);
$captionHeading = $_SESSION['dept'];
$conn = connect();
$attrs = array( 'id' => 'main',
'width' => '100%',
'Border' => '1');
$table = new HTML_Table($attrs);
$table->setAutoGrow(true);
$table->setAutoFill('n/a');
$sql_assets = "select AssetName, AssetID
from Assets
where Assets.DepartmentID = $_SESSION[deptID]";
$stmt1 = sqlsrv_query($conn, $sql_assets);
if ($stmt1)
{
$rows = sqlsrv_has_rows($stmt1);
if ($rows === true)
{
while( $row = sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) )
{
$assetName [] = $row['AssetName'];
$assetID [] = $row['AssetID'];
}
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
$i = 0;
foreach($assetName as $val)
{
$table->setHeaderContents(0, $i++, $val);
unset($val);
}
sqlsrv_close($conn);
$conn = connect();
$tsql = "select + 'Job#' + CAST (JobNum AS VARCHAR(10))+ ' ' + Description AS newField, datediff(MI,StartTime, EndTime) / 15 as 'RowSpan', AssetName, AssetID
from Calendar_View, Departments, Status, Assets
where Departments.DepartmentName = '$captionHeading' and Calendar_View.Department = Departments.DepartmentID and AssetStatus = Status.StatusID and
Calendar_View.Asset = Assets.AssetID
order by AssetID asc";
$rowcounter = 1;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
for ($i = 0; $i < count($assetID);$i++)
if ($row['AssetID'] == $assetID[$i])
$table->setCellContents($rowcounter++,$i,$row['newField']);
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
echo $table->toHTML();
?>
</body>
</html>
$headerCounter = 0;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
$rows = sqlsrv_has_rows($stmt);
if ($rows === true)
{
$cellCounter = 1;
$cellPosition = 0;
$rowCounter = 1;
echo "Header position outside of loop: $headerCounter ";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
if ($row['AssetID'] == $assetID[$headerCounter])
{
echo "<br>begining of if statement<br>";
echo "Header (beginning of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (beginning of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
echo "<pre>";
var_dump($row);
echo "</pre>";
/*foreach ($row as $result)
{
echo "<pre>";
var_dump($result);
echo "</pre>";
}*/
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
//echo "$headerCounter";
//echo "<br>";
echo "Header Name (end of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (end of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
//$cellPosition++;
$rowCounter++;
echo "end of if statment<br><br>";
}
else
{
echo "<br>header before increase $headerCounter";
echo "<br>header name outside of loop, before increment $assetName[$headerCounter]";
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
echo "<br>header name outside of loop, after increment $assetName[$headerCounter]";
echo "<br>header increased by 1, now: $headerCounter";
}
}//$headerCounter++;
//$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
}
Ok, the problem was that I was not incrementing the rowcounter variable after i left the initial loop. The following line:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
Should have been:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter++,$cellPosition,$row['newField']);
Sorry for the poor formatting of the original post. I am not sure what went wrong.
I have two arrays in my php that I want to print. I want them to be concatenated but I don't know how. The array for the $names prints but the description array "$desc" does not. is there any way to print both together?
$query = "SELECT eName FROM Events";
$query2 = "SELECT eDescription FROM Events";
$result = mysql_query($query);
$result2 = mysql_query($query2);
$names = array();
$desc = array();
echo "hello there people!" . $query . " ".$result;
for($i=0; $i<sizeof($result); $i++){
echo $result[$i] ."\n" . $result2[$i];
}
while($entry = mysql_fetch_row($result)){
$names[] = $entry[0];
}
while($entry2 = mysql_fetch_row($result2)){
$desc[] = $entry2[0];
}
echo "Which Event would you like to see?<br>";
$stop = count($names);
//echo $stop . "\n";
$i = 0;
print_r($names);
print_r($desc);
foreach($names as $value){
echo $value . " " . $desc[i] ."<br>";
$i++;
}
Why are you doing two queries to get data from the same source?
$sql = mysql_query("select `eName`, `eDescription` from `Events`");
while($row = mysql_fetch_assoc($sql)) {
echo $row['eName']." ".$row['eDescription']."<br />";
}
Much simpler.
Try this:
foreach($names as $key => $value){
echo $value . " " . $desc[$key] ."<br />";
}
As long as the array $key match, the information will be printed together.
I'm trying to write a relatively simple twitter query in php with result like this:
from:TravisBenjamin3 OR from:AshleyElisaG OR from:tncvaan ...
This code works accept it doesn't echo the second OR, also I don't want to display an OR on the last row.
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < count($row)) {
echo " OR";
}
}
Some help would be greatly appreciated. Thanks,
<?php
$tweets = array();
while($row = mysql_fetch_array($result)) {
$tweets[] = $row['twitter'];
}
if(count($tweets) > 0) {
echo "from:" . implode(" OR from:", $tweets);
}
?>
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < $rowCount) {
echo " OR";
}
}
$count = mysql_num_rows($result);
for($r = 0; $r < $count; $r++)
{
$row = mysql_fetch_array($result));
echo " from:";
echo $row['twitter'];
if ($r < ($count - 1))
{
echo " OR";
}
}
Or, even easier:
$search = "";
while($row = mysql_fetch_array($result))
{
$search .= " from:" . $row['twitter'] . " OR";
}
// Cut the last " OR"
$search = substr($search, 0, strlen($search) - 3);
echo $search;
Which is actually a poor man's implementation for implode() suggested by Aaron W..