I'm trying to select values where another POST values are an array, I do not know what is wrong with my query giving me this error. I'm trying to know what courses are just added to table. I have five inputs in the form.
Notice: Trying to get property of non-object in C:\Apache\htdocs\xxx\addcourse.php on line 262
Here is my code
<?php
if(isset($_POST['Submit'])) {
$code= isset($_POST['code']) ? $_POST['code'] : '';
$coursecode = isset($_POST['coursecode']) ? $_POST['coursecode'] : '';
$both=$code[$x] .' '. $coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
if ($resultcourses->num_rows > 0) {
while($row = $resultcourses->fetch_assoc()) {
?>
</p>
<p> </p>
<p> </p>
<table width="415" border="0">
<tr>
<?php
$courses=$row["course_code"];
echo $courses;
?>
</div>
</tr>
</table>
<?php
}
}
}
?>
First, you build an array of the course codes that you want to retrieve; I'm leaving off the boundary checks for simplicity:
$codes = [];
foreach ($_POST['code'] as $k => $code) {
$codes[] = $code . ' ' . $_POST['coursecode'][$k];
}
Then, you prepare the statement you will use:
$stmt = $mysqli->prepare("SELECT *
FROM courses
WHERE course_code = ?
ORDER BY course_id DESC
LIMIT 5");
Followed by the main loop:
foreach ($codes as $code) {
$stmt->bind_param('s', $code);
assert($stmt->execute());
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
// ...
}
}
you can try this way with small modified code
first you have to convert string to array to get index (x) in array
$code = explode(" ", $code);
$course = explode(" ", $coursecode);
foreach ($code as $cd => $x) {
$both = $code[$x].' '.$coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
}
second you can choose variable $code or $course as length of loop based on your case
foreach ($course as $crs => $x) {
your condition...
}
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;
}
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;
}
I have problem in returning the first key of array in foreach. I can return the $key but i cant figure out on returning the first $key only.
<td>
<div align="center">
<span class="formlist">
<select id="plant" name="plant[]" class="form-control" multiple="multiple">
<?php
$query_plant = "SELECT * FROM plant WHERE plant_enable=1 ORDER BY plant_name";
$rs_plant = DB_Query($query_plant);
while ($row_plant = DB_FetchRow($rs_plant)) {
$plant.='<option name='.$row_plant["plant_shortname"].' value='.$row_plant["plant_id"].'>' .$row_plant["plant_name"].' ['.$row_plant["plant_id"].']</option>';
}
mysql_free_result($rs_plant);
echo $plant;
?>
</select>
</span>
</div>
</td>
if(isset($_POST['plant'])) {
$checkbox1 = $_POST['plant'];
$chk="";
$stf_sql = "SELECT * FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$stf_res = DB_Query($stf_sql);
if(DB_RowsReturned($stf_res) > 0) {
$del_sql = "DELETE FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$del_res = DB_Query($del_sql);
}
foreach($checkbox1 as $chk1)
{
$in_ch="insert into test_plant(staff_id, plant_name, submit_dt) values ('$STAFF_ID','$chk1', Now())";
$in_res = DB_Query($in_ch);
$abc = mysql_query("SELECT * FROM test_plant");
while($abc_row = mysql_fetch_assoc($abc)) {
foreach($abc_row as $key => $value) {
echo $key; //return first key here
}
}
}
} else {
echo "OK";
}
I have tried returning $key[0] but it returns the first letter only. I want to return 'p_id'
Like this,
$keys = array_keys($checkbox1);
print_r($keys); // for all keys
echo $keys[0]; // It will echo first key of the array.
You could reset the internal array pointer and then get the key of the current element:
reset($checkbox1);
echo key($checkbox1);
(Put this outside your outermost while loop).
Or you could even get all the array keys, and then grab the current key:
echo current(array_keys($checkbox1));
I selected an array of product IDs and product names from the table product. I tried to echo out only one product name from the array, but all I got was the first letter of the product name. Below is my code. Thanks in advance for any tips.
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];
Add brackets to the variables inside the while loop to create the array
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}
echo $productname[0];//this will print the first productname
I think is better make just 1 array of objects
$array=array();
while ($userinfo1 = $info1->fetchobject()) {
$array[] = $userinfo1;
}
echo $array[0]->productname;
instead of doing this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];
Do this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
$counter =0;
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
echo $productid[counter];
echo $productname[counter];
counter++;
}
this way you'll echo out every value of the array
You have various options at your disposal. Take your look for instance, you could create an associative array like the following:
$items = array();
while ($userinfo1 = $info1->fetchobject()) {
$item = array(
'productid' => $userinfo1->$productid,
'productname' => $userinfo1->$productname
);
array_push($items, $item);
// or you could use native
// $uitems[] = $item;
}
That would give you an array ($users) that you could loop through and fetch for set index:
foreach($items as $item) {
print_r($item); // prints the whole user item.
//print $item['productid']; /* or even print the users product id.*/
}
Or simple for one item like you requested:
echo $items[0]['productid'];
Alternatively: if you'd like seperate arrays, you could do as stated in the other answers:
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}
I'm hoping someone can help.
I'm sure its just a simple one that I just can't work out for some reason.
Basically I have up a class that handles all my database functions (connect, select, insert, update).
In the select function I am returning an array.
public function getAll($table, $cols, $where, $limit, $order) {
// Set the query variables
if($cols == '') {
$cols = '*';
}
if($where!='') {
$where = ' WHERE '.$where;
}
if($limit!= '') {
$limit = ' LIMIT '.$limit;
}
if($order!='') {
$order = ' ORDER BY '.$order;
}
// Make the query string
$sql = 'SELECT '.$cols.' FROM '.$table.$where.$order.$limit;
//echo $sql;
// Set the query
$news_qry = mysql_query($sql);
// Set the array
$rows = array();
// Run a loop through the results
while($item = mysql_fetch_object($news_qry))
{
// Add each row to an array.
$rows[] = $item;
}
return $rows;
}
This function is working as I can print an array. See below:
Array ( [Gallery_id] => 1 [Gallery_Name] => Test [Gallery_FolderName] => Test Folder )
But when I go to use the object -
$arr_GalleryInfo = $dataObj->getAll('tbl_Gallery', '', '', '', '');
Within the for each loop (see below) I only get the first letter of the result from the database.
<?php
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
?>
<tr>
<td>
<?php echo $arrGallery['Gallery_Name']; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
</tr>
<?php
}
?>
Any help would be great.
Thanks.
Replace:
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
etc...
with:
foreach ($arr_GalleryInfo as $arrGallery)
{
etc...
Well, your big issue is that you're trying to iterate over the 0-index of an array.
foreach ($arr_GalleryInfo[0] as $arrGallery) // get rid of the `[0]`.
That will make it so that you actually get some legit iteraction, but there are some other things which are gotchas that you're about to hit.
// this will output `Array`. You want $artGallery['Gallery_FolderName']
// or $artGallery['Gallery_id']
echo $arrGallery;
Of course, you could avoid that whole second issue with a nested loop:
foreach ($arr_GalleryInfo as $arrGallery) {
echo '<tr>';
foreach($arrGallery as $val ) echo "<td>$val</td>";
echo '</tr>';
}
If $news_qry = mysql_query($sql); fails, you'll have nothing to warn you if something breaks. You should make it: $news_qry = mysql_query($sql) or die(mysql_error());
And, of course, you should use mysql_real_escape_string on all of your db inputs.