Get value from SQL database - php

I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks

Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.

Related

Php to Excel : fill the output Excel file with a loop

I want to create an Excel file (with PhpExcel) and fill it with the content of a MySQL query.
I only have one column so the result will look like this :
$sheet->setCellValueByColumnAndRow(0, $i, $content)
So I have to loop inside my query and create a counter to fill each row corresponding to each item of the column ptlum of my content.
So the goal is to have the following result :
1 AX001
2 AX003
3 AX012
The code is the one :
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, $column, $data['ptlum']);
//echo($column. " " . $data['ptlum']. " ");
$column = $column + 1; //or $column++;
The problem is that my Excel file is empty..
If i put a number instead of $column in the setCellValueByColumnAndRow line it works. But the variable does not work..
On the other hand if I put "$column = 1;" inside the loop, my Excel file will always contain one only row..
Have you an idea ?
Thank you very much !
You just have to change the call to setCellValueByColumnAndRow for each column and increment it:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
As you see, you can retrieve the field/column you want with mysql_fetch_assoc, returning an associative array.
Also, you don't have to include the field(s) of your WHERE condition(s) in the SELECT.
Then finally, you should replace the deprecated mysql_* function by their equivalents mysqli_*, as explained here.
Edit:
For your "new" problem, this code should work:
$sql = "SELECT ptlum FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$row = 1; // 1-based index
$column = 1;
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow($column, $row, $data['ptlum']);
$column = $column + 1; //or $column++; if you prefer
}
First, don't instanciate your workbook and sheet in each loop, do it before, once.
Second, you had your arguments in the wrong order, it's column then row, not the inverse, as explicited in the method name.
Maybe this is the thing you wanted:
$sql = "SELECT ptlum, RIGHT(date,4) FROM `ptlum` WHERE nomcom = 'AIGREFEUILLE' and RIGHT (date,4) < 2015 and RIGHT(date,4) > 0 ";
$result = mysql_query($sql);
$i = 0;
while($data = mysql_fetch_assoc($result)) {
$sheet->setCellValueByColumnAndRow(0, $i, $i+1); //1-based index
$sheet->setCellValueByColumnAndRow(1, $i, $data['ptlum']);
$i++;
}

Sort a while loop using exploded variable

I have got the following, but in the results is a long string, contained within that string is a server name which I am wanting to sort the results by, is this possible?
<?php
$dbQuery = mysql_query("SELECT * FROM opencall where cust_id = 'user.name#jpress' and status < 6 order by fixbyx asc") or die(mysql_error());//find call ref of open call with correct id
while ($PRTGdbresults = mysql_fetch_array($dbQuery)){
$SplitText = explode("\n", $probtext); //split the string by line break
echo'<div class="row">';
echo'<div class="inf_div" title="Current Server">';
echo $SplitText[1]; //this is the server name I wish to sort by
echo'</div></div>';
}
?>
You can define your own function for sorting and then use this function with the usort sorting function.
Using the code you gave I will simply compare the strings of the server names and sort them in alphabetical order. Here is the code;
<?php
$dbQuery = mysql_query("SELECT * FROM opencall where cust_id = 'user.name#jpress' and status < 6 order by fixbyx asc") or die(mysql_error());
$results = array();
while ($PRTGdbresults = mysql_fetch_array($dbQuery)){
array_push($results,$probtext);
}
usort($results, "sortProbtext");
foreach($results as $key => $probtext){
$SplitText = explode("\n", $probtext);
echo'<div class="row">';
echo'<div class="inf_div" title="Current Server">';
echo $SplitText[1];
echo'</div></div>';
}
function sortProbtext($a, $b){
$SplitTextA = explode("\n", $a);
$SplitTextB = explode("\n", $b);
if ($SplitTextA[1] == $SplitTextB[1] ) {
return 0;
}
return ($SplitTextA[1] < $SplitTextB[1] ) ? -1 : 1;
}
?>

To prevent sql-injection, is it sufficient for mysqli_real_escape_string() to be applied only once to a comma separated string?

I apologize if someone posted this and I missed it...I googled and scanned SO for a similar question and if it exists, I missed it.
Scenario: user enters comma separated input. The string needs to be exploded and each piece used to update different table row. Is it sufficient to apply mysqli_real_escape_string() once:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", mysqli_real_escape_string($cxn, $_GET['userinput']));
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '$myID'");
}
?>
or must each pass through the for loop apply mysqli_real_escape_string?
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '".mysqli_real_escape_string($cxn, $myID)."'");
}
?>
So, apply it once on the comma-separated string and explode the string, or explode the string and then apply it for each iteration of the for loop?
By using prepared statements you don't have to worry about escaping the content yourself, or how to properly do it.
Example:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
// replace your raw var with ? in the sql statement
$sql = "UPDATE myTable SET myValue = 'y' WHERE id = ?";
// run the prepare method
$stmt = $conn->prepare($sql);
// bind the '?' in the sql statement to $myID of type int
// I'm assuming it's an int here, if it's a string change the 'i' to an 's'
$stmt->bind_param('i', $myID);
// and run it
$stmt->execute();
}
?>
Some further reading, examples, and discussion.

Saving while results into an array

I am trying to query a database with a new 'WHERE (AND)' clause on each loop. The new clause is simply the number of the loop.
I need to save the count of rows returned per loop in an array which I am struggling with.
If for instance there is two loops, the first loop returns 2 rows, the second 3. I want the array to essentially be:
$portfolio_list = array(2,3);
Here is as far as I have managed to get, and no surprise its not working correctly.
Any help would be great!
$portfolios = 2;
$i = 1;
$portfolios_list = array();
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->EE->db->query($portfolio_sql);
$return = $query->result();
$portfolios_list[] = $return;
$i++;
}
please try this
$portfolios = 2;
for ($i = 1; $i < $portfolios+1; $i++) { //this runs 2 times
$where_array = array('member_id' => $member_id, 'type_id' => '1', 'portfolio_number' => $i);
$this->db->where( $where_array );
//$this->db->select('*'); // I guess you do not need select for this
$portfolio_list[$i] = $this->db->get('exp_submissions')->num_rows();
}
var_dump($portfolio_list);
Try this
$portfolios = 2;
$i = 1;
while ($i <= $portfolios) {
$portfolio_sql = "
SELECT COUNT(portfolio_number) AS portfolio_uploaded_images
FROM exp_submissions
WHERE member_id = $member_id
AND type_id = '1'
AND portfolio_number = $i
";
$query = $this->db->query($portfolio_sql);
$portfolios_list[$i] = $query->num_rows; // This will give the No of rows fetched
$i++;
}
foreach($portfolios_list as $row => $no)
{
echo "The Results Fetched from query no ".$row." is ".$no;
}

Array output or json output without quotes

How i can output my array without quotes on this situation
for($i=1; $i <= date("d"); $i++) { $days[] = $i; }
echo json_encode($days); // ouput [1,2,3,4,5,6,7,8,9,10]
This first on is fine, but on the second one
for($i=1;$i <= date("d"); $i++) {
$Sql = "SELECT COUNT(Stats_Clicks) AS Total FROM tabstats WHERE DAY(Stats_Date) = $i
AND MONTH(Stats_Date) = $month
AND YEAR(Stats_Date) = $year
";
$Query = mysql_query($Sql,$Conn) or die (mysql_error($Conn));
$Rs = mysql_fetch_array($Query);
$clicks[] = $Rs['Total'];
}
echo json_encode($clicks);
json output returns this
["1","1","0","0","0","0","0","0","0","0","0"]
i need this without quotes on this format.
You just need cast to integer.
$clicks[] = (int)$Rs['Total'];
Untested:
$clicks[] = (int) $Rs['Total'];
try array_map with intval function
like this:
echo json_encode(array_map("intval",($Rs['Total'])));
example:
print_r(json_encode(array_map("intval",array("1","2","3"))));
=> [1,2,3]

Categories