I have a SQL query and an array where I put values to exclude. When I perform my query, I would like to test my variable.
If not empty ==> Display values
If empty ==> Display one time 0 result.
My SQL query gives in output these values:FGFR1e12, FGFR3e7, FGFR3e14
When I perform my php script, I manage to display values but it doesn't enter in the loop else when the variable is empty.
Does anyone know what I am doing wrong in my script ?
Here's my script:
<?php
require_once ('config.php');
$VariantNContrib = "SELECT DISTINCT Reference FROM mytable";
$PerformVariantNContrib = mysqli_query($conn, $VariantNContrib) or die(mysqli_error($conn));
// Values to exclude are stored in an array
$arrayNoContrib = array(
'FGFR1e12',
'FGFR3e7',
'FGFR3e14'
);
while ($rowVarNContrib = mysqli_fetch_assoc($PerformVariantNContrib)) {
if (!in_array($rowVarNContrib["Reference"], $arrayNoContrib)) {
$NContribList = '' . implode(',', $rowVarNContrib) . '; ';
if (!empty($NContribList)) {
echo '<br/>Variants:' . $NContribList . '<br/>';
}
else {
echo "0 results";
}
}
}
?>
Your code should be:-
$arrayNoContrib=array('FGFR1e12', 'FGFR3e7', 'FGFR3e14');
while($rowVarNContrib = mysqli_fetch_assoc($PerformVariantNContrib)) {
if(!empty($rowVarNContrib) && !in_array($rowVarNContrib["Reference"],$arrayNoContrib)){ // check $rowVarNContrib array is not empty
$NContribList=implode(',',$rowVarNContrib); // remove empty string
echo "Variants: $NContribList"."<br>"; // remove earlier <br>
}else{
echo "0 results"."<br>"; // add <br>
}
}
Hi I dont know why you have used implode if i am right. You have a array in which you have some values and you are fetching some reference and if all are same then you are displaying 0 result and if not then you are displaying that refence number. Then Please once try this one.
<?php
require_once ('config.php');
$VariantNContrib="SELECT DISTINCT Reference FROM mytable";
$PerformVariantNContrib=mysqli_query($conn,$VariantNContrib) or die(mysqli_error($conn));
//Values to exclude are stored in an array
$arrayNoContrib = array(
'FGFR1e12',
'FGFR3e7',
'FGFR3e14'
);
$i = 0;
while($rowVarNContrib = mysqli_fetch_assoc($PerformVariantNContrib)) {
if (!in_array($rowVarNContrib["Reference"], $arrayNoContrib)) {
$NContribList = trim($rowVarNContrib["Reference"]);
if (!empty($NContribList)) {
echo '<br/>Variants:' . $NContribList . '<br/>';
$i++;
}}
}
echo $i." results";
empty() function does not return true for string which is single space. " ".
$NContribList=''.implode(',',$rowVarNContrib).' ';
In above code you've space at the end of the string and that is the reason empty() is returning FALSE.
Either remove that space from the string or use PHP trim() to remove unnecessary spaces.
Related
I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.
I have two HTML pages inside a session. On my first page, I want to create an array, which is saved in a $_SESSION variable. On the second page, I want to display my array.
PHP code for my first page looks like that:
<?php
include ("../script/db_connect.php");
$select_questions = 'select * from questions ';
if (isset($_POST["own"]) && $_POST["own"] == "No") {
$select_questions .= 'where creator != '
. $_SESSION["id"];
}
$select_questions .= 'limit 3';
$questions_result = mysqli_query($con, $select_questions);
$_SESSION["questions"] = mysqli_fetch_assoc($questions_result);
mysqli_close($con);
?>
PHP code on my second page looks like that:
<?php while ($array = $_SESSION["questions"]) {
echo $array["question"]; } ?>
When I go to second page, an infinite loop is displayed, where only the first element of my array is displayed over and over again. What is the reason for that? I cannot find any mistake in my code.
Change this
$_SESSION["questions"] = mysqli_fetch_assoc($questions_result);
to (here we fetch all rows from the sql result, not only one)
while($row=mysqli_fetch_assoc($questions_result)) $_SESSION["questions"][] = $row;
And later do
foreach($_SESSION["questions"] as $quest) { echo $quest["question"]; }
I'm trying to list data from my database, and I need to use variables inside of my array, but when echoing it I want it to remove the last comma but it doesn't seem to work.
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = '1'");
while($forum_usersonline_fetch = $forum_usersonline->fetch_array()) {
$usersonlineuname = $forum_usersonline_fetch["user_name"];
$onlinelist = array($usersonlineuname, ' ');
echo implode($onlinelist, ',');
}
It always returns with user1, user2, so how should I do it?
Your can do this job easily in sql. If your database is mysql try following
SELECT GROUP_CONCAT(user_name) as user_name FROM users WHERE user_loggedin = '1'
or if your database is postgres try following
SELECT string_agg(user_name, ',') as user_name FROM users WHERE user_loggedin = '1'
above query result return comma separated user_name.
You could use chop(); which removes characters from the right end of a string.
An example:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo chop($str,",");
?>
Or you could use rtrim(); like:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo rtrim($str,',');
?>
Or you could also use substr like:
<?php
$str = "Random String Ending With,";
echo substr($str,0,-1)."<br>";
?>
use rtrim(string,',')
For reference goto http://www.w3schools.com/php/func_string_rtrim.asp
The problem is you're doing the implode inside the while loop, it should be done outside after building your final array. This is what I would do:
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = 1");
while ($row = $forum_usersonline->fetch_array()) {
$onlinelist[] = $row["user_name"];
}
echo implode($onlinelist, ",");
However, this should not be the case as you should be using CONCAT when doing your database query.
My Php code is
<?php
include('session.php');
include('db.php');
$session=$_SESSION['agent'];
$home1 = "SELECT fullname FROM users WHERE role='$session'";
$result1=mysql_query($home1) or die(mysql_error());
while ($row1=mysql_fetch_array($result1)) {
echo $gallery = "'".$row1[0]."',"; // output is 'sam','teja','multiplevaluessoon',
$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
$result=mysql_query($home) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$msg =$row["message"];
echo $randomUserId=$row["from"];
echo $msg . "<br/>";
}
?>
here $gallery contains ',' comma at the end, so i am getting a error in where clause, when i am trying to trim the output of $gallery
'sam','teja','multiplevaluessoon',
last charcter inside loop i am getting
'sam''teja''multiplevaluessoon'
which is trimming all the commas due to while loop, i need last comma to be trimmed so that i can execute it in where clause
please suggest me any ideas
Make use of rtrim().
$yourfinaltext = rtrim($yourcommadelimitedstring, ',');
Change your while like this.
while ($row1=mysql_fetch_array($result1)) {
$gallery .= "'".$row1[0]."',";
$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
echo rtrim($gallery,',');
$rest = substr("abcdef", 0, -1); // returns "abcde"
http://php.net/manual/en/function.substr.php
Remove comma as this...
$gallery=substr_replace($gallery ,'',0,1);
I am having problems with the retrieval of data from my database using a where clause with a for loop variable. this codes currently can retrieve the data from the database but however the values retrieved from the database stockpiles. at the number 1 in the for loop its still fine. but when it goes to the next one. the data gathered is the combination of 1 and 2. when it finally hit the end of the loop all of the data is displayed.
Which part of the codes must be edited to change the display of data to non-cumulative
<?php
$sectorcount = $row_SectorCount['COUNT(*)'];
//number of rows in database
$spendingname= array();
$spendingpercent= array();
$spendingid= array();
?>
// Add some data to the details pie chart
options_detail_1.series.push({ name: 'Tax Spending Detail', data: [] });
$(document).ready(function() {
chart_main = new Highcharts.Chart(options_main);
chart_detail_1 = new Highcharts.Chart(options_detail_1);
})
function push_pie_detail(sectorid) {
switch(sectorid)
{
<?php
for ($i=1; $i<=$sectorcount; $i++)
{
echo "case 'sector".$i."':" ,
"setTimeout", "(" , '"chart_detail_1.series[0].remove(false)", 1000);' ,
"chart_detail_1.addSeries(options_detail_1, false);" ,
"chart_detail_1.series[1].setData( [";
mysql_select_db($database_conn2, $conn2);
$query_Spending = "SELECT CONCAT(spending.SectorID, spending.ExpenditureID) AS 'SpendingID',
expenditure.ExpenditureName, spending.SpendingPercent, spending.SectorID
FROM spending
INNER JOIN expenditure ON spending.ExpenditureID = expenditure.ExpenditureID
WHERE spending.SectorID = '.$i.'";
$Spending = mysql_query($query_Spending, $conn2) or die(mysql_error());
$totalRows_Spending = mysql_num_rows($Spending);
while($row_Spending = mysql_fetch_assoc($Spending))
{
$spendingname[] = $row_Spending['ExpenditureName'];
$spendingpercent[] = $row_Spending['SpendingPercent'];
$spendingid[]= $row_Spending['SpendingID'];
}
mysql_free_result($Spending);
$a = 0;
foreach ( $spendingid as $sgi => $sgid)
{
if ($a > 0) echo ', '; // add the comma
echo "{
name: '$spendingname[$sgi]',
y: ". $spendingpercent[$sgi] * $tax .",
id: ' $sgid',
}";
$a++;
}
echo "], false);" ,
"chart_detail_1.redraw();",
"break;";
}
?>
default:
break;
}
}
You need to wrap your variable in 'x' single quotes in your where clause, otherwise it will think you mean id = true, which is true for all of them =) I had the same problem recently
EDIT: So instead of saying where spending.SectorID = $i, you should have 'somevalue', just make a new variable $example = "'" . $i . "'", and use that variable in the where clause
I wrote a function that takes text and wraps it in single quotes just for this situation
Move your $spendingname = array(); and other array definitions inside the loop.