How do i use where clause for array if value[3] has multiple data stored
$fsql="select * from Error where RptDatime = 201706091000 and partnumber like ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}
You can use regex function instead of like. Below is the sample code for you.
$partnumner = [];
foreach($value[3] as $v)
{
$partnumber[] = "*.".$v.".*";
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
If you still wish to use like, you can follow the answer here
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.
if(!isset($value[3])){
return false;
}
if(!is_array($value[3])){
return false;
}
foreach($value[3] as $number){
if(!is_numeric($number)){
return false;
}
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}
Related
I want to sort a returned value from a while loop here is my code
public function Getter($stream){
$sql1 = "SELECT reg_no FROM hs_registration ";
$sql1.= "JOIN hs_students USING(reg_no) WHERE class_id = 2";
$result1 = $database->query($sql1);
$num1 = $database->num_rows($result1);
if($num1 > 0){
$records = array();
$number_of_sub = getNoSub();
while($row = mysqli_fetch_array($result1)){
//return individual score
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$records[] = number_format($flyAvg,2).' '.$row['reg_no'];
}
}
return $records;
}
$averages = Getter($stream);
foreach ($averages as $avg){
echo $avg
}
Please, I want to sort the output based on the avg with the students reg_no appended to it
Output
54.20 FMS34
91.00 FMS51
72.16 FMS64
44.81 FMS23
68.52 FMS30
48.65 FMS37
My desired output is
Output
91.00 FMS51
72.16 FMS64
68.52 FMS30
54.20 FMS34
48.65 FMS37
44.81 FMS23
If your leading numbers are always two digits, then a decimal point, the two digits, then rsort($records); would suffice.
If they might be anything else, then keep a separate sorting array, then use array_multisort() to modify the $records.
public function Getter($stream): array
{
$sql = "SELECT reg_no
FROM hs_registration
JOIN hs_students USING(reg_no)
WHERE class_id = 2";
$flyAvgs = [];
$records = [];
$number_of_sub = getNoSub();
foreach ($database->query($sql) as $row) {
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$flyAvgs[] = $flyAvg;
$records[] = number_format($flyAvg, 2) . ' ' . $row['reg_no'];
}
array_multisort($flyAvgs, SORT_DESC, $records);
return $records;
}
I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';
I have been trying to convert the fields from a mysql_fetch_array (that are urlencoded) to urldecode before converting to JSON (json_encode)
Here's what I'm working with that doesn't work:The output is still urlencoded
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_fetch_array(mysql_query($query));
foreach($result as $value) {
$value = urldecode($value);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
Any ideas?
yeah....! you're not updating $result with the value returned by the function. $value needs to be passed by reference.
foreach($result as &$value) {
$value = urldecode($value);
}
or
foreach($result as $i => $value) {
$result[$i] = urldecode($value);
}
when you do this...
foreach($result as $value) {
$value = urldecode($value);
}
The result of the function is lost at at iteration of the foreach. You're trying to update each value stored in $result but that's not happening.
Also take note that the code only fetches one row from your query. I'm not sure if that's by design or not.
Try:
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_query($query);
$value = array();
while($row = mysql_fetch_array($result))
$value[] = urldecode($row);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}
Can I loop through DB results and remove Slashes?
(I started getting more slashes everytime I edited the text and put it back into the DB)
$db = new connection();
$query = "SELECT * FROM ITEMS, ALPACA_SALES WHERE ITEMS.uid = '$id' AND ALPACA_SALES.uid = ITEMS.uid";
$results = $db->query($query);
$data = array();
while($info = mysql_fetch_array($results))
{
$data[] = stripslashes($info);
}
But I am getting the following error:
Notice: Array to string conversion in /home/content/myfile.php on line 78
When I add the data to the database I do the following:
if (!empty($_POST['more_text']))
{
$more_text = addslashes($_POST['more_text']);
}
else
{
$error = false;
$error_message = "Please add a description.";
}
And then I use UPDATE for the insert into the DB:
$query2 = "UPDATE ALPACA_SALES SET more_text = '$more_text' WHERE uid = '$id'";
$result = $db->query($query2);
You can't run stripslashes() on an array, which is what $info is from storing mysql_fetch_array($results). You could iterate through $info and strip slashes on each entry, or explicitly strip slashes if you don't need to do all of them.
$i=0;
while($infoarray = mysql_fetch_assoc($results))
{
foreach($infoarray as $field=>$value){
$data[$i][$field] = stripslashes($value);
}
$i++;
}
Edit: You can also create a small function to strip slashes in an array, as outlined in the documentation here: http://us.php.net/manual/en/function.stripslashes.php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
Do not do that. stripslashes() is not enough to make a string safe to use in an SQL statement. Your code is vulnerable to SQL injection. Use prepared statements and bound parameters instead.