I'm a new user of CodeIgniter 4. I got this error when I want to show 'prodi_name' of table 'prodi' on a form.
This is my ProdiModel
protected $table = 'prodi';
protected $primaryKey = 'id_prodi';
public function getProdi($id = false)
{
if ($id == false) {
return $this->findAll();
}
return $this->where('prodi_code', $id)->first();
}
I have setting my BaseController with
$this->prodiModel = new \App\Models\ProdiModel();
so my Controller is
public function add()
{
$data = [
'title' => 'Admin',
'prodi' => $this->prodiModel->getProdi(),
'validation' => \Config\Services::validation()
];
return view('admin/add', $data);
}
And this is my form, I want to show the prodi_name on a multiple select field
<div class="form-group">
<label>Prodi</label>
<select class="form-control select2 multiple" id="prodi" name="prodi[]" multiple="multiple" data-placeholder="Select prodi">
<?php
foreach ($prodi as $prodi) :
echo "<option value='" . $prodi["prodi_name"] . "'";
if (old('prodi')) {
if (in_array($prodi['prodi_name'], old('prodi'))) echo "selected";
}
echo ">" . $prodi['prodi_name'] . "</option>";
endforeach; ?>
</select>
</div>
Please help me to solve this problem. Thanks
first of all in CI 4 there is no first() method,
use
public function getProdi($id = false)
{
if ($id == false) {
return $this->findAll();
}
return $this->where('prodi_code', $id)->getFirstRow(‘array’);
}
On the second thought you are returning two types of data here, if id is false you return multidimensional array and if id is there code returns single row.
Again in the same method, you have called findAll(), if it returns and associative array, your code should run, but if that returns a object then you should change to,
<?php
foreach ($prodi as $prodi) :
echo "<option value='" . $prodi->prodi_name . "'";
if (old('prodi')) {
if (in_array($prodi->prodi_name, old('prodi'))) echo "selected";
}
echo ">" . $prodi->prodi_name . "</option>";
endforeach; ?>
Related
I have a registration system where there are several fields. One of the registration fields is Segments and they come from the database:
public function comboSegmentos($key)
{
$sqlMostrar = mysqli_query($this->conexao, "SELECT * FROM loja_segmentos;");
if (mysqli_num_rows($sqlMostrar) == 0)
{
$mostrar = "<div style='color: red'>Nenhuma segmento cadastrado até o momento.</div>";
}
else
{
$mostrar = "<select name='Segments[]' id='segmentos' class='form-control select2' multiple='multiple' style='width: 35%'>";
while ($jmMostrar = mysqli_fetch_object($sqlMostrar))
{
$mostrar .= "<option value='".$jmMostrar->Segmentos."' ".$selected.">".$jmMostrar->Segmentos."</option>";
}
$mostrar .= "</select>";
}
return $mostrar;
}
So that the method doesn't have too many parameters, I did it like this:
<?php
...
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados);
Method cadastrarProdutos($dados)
But I'm not able to get the values of the Segments even using foreach().
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
foreach($segments as $seg)
{
$segm = $seg;
}
...
}
How can I get the values of the select2 field and get them using a PHP method without Jquery?
I managed to solve it as follows:
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
$segm = array();
foreach($segments as $seg)
{
$segm[] = $seg;
}
$segments = implode(',',$segm);
...
}
Here's the error i'm getting :
syntax error, unexpected end of file, expecting function (T_FUNCTION)' in D:\User\Documents...\Controllers\DeviceController.php:68
It happens in this code :
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Data\Campaign;
use App\Data\Device;
use App\Helpers\Database;
use App\Helpers\DateHelpers;
use App\Helpers\ProfileHelpers;
use App\Helpers\Utils;
use Illuminate\Http\Request;
class DeviceController extends ApiController
{
public function show($deviceId)
{
return Device::find($deviceId);
}
public function update(Request $request, $deviceId)
{
$isAlertActive = filter_var($request->input('isAlertActive'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter5Pushes = filter_var($request->input('isAlertAfter5Pushes'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter10Pushes = filter_var($request->input('isAlertAfter10Pushes'), FILTER_VALIDATE_BOOLEAN);
$hasAtLeastOneSettingActive = $isAlertActive || $isAlertAfter5Pushes || $isAlertAfter10Pushes;
$settings = [
'is_alert' => $isAlertActive,
'is_alert_after_5_pushes' => $isAlertAfter5Pushes,
'is_alert_after_10_pushes' => $isAlertAfter10Pushes
];
if ($isAlertActive) {
$settings['alert_seuil'] = intval($request->input('alertThreshold'));
$settings['alert_votemini'] = intval($request->input('minVoteCountBeforeAlert'));
}
if ($hasAtLeastOneSettingActive)
$settings['next_alert_in_hours'] = intval($request->input('nextAlertInHours'));
Device::where('id_device', $deviceId)
->update($settings);
}
/////////////////////////////////////////////////////////////////////////////
public function putInLocation($sectionId, $locationName)
{
$section = Section::find($sectionId);
if ($section && $section->area->id_client == $this->clientId) {
Location::createLocation($sectionId, $locationName);
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
public function delete($locationId)
{
$location = Location::find($locationId);
if ($location && $location->section->area->id_client == $this->clientId) {
$location->delete();
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
}
?>
I don't see any syntax error there, i checked the brackets multiple times but maybe i missed something ?
What's weird for me is that there is no syntax error until i add a foreach in another file (D:\User\Documents...\Views\Partials\areasettings.php). Here's the foreach :
<div class="col-lg-3 col-lg-offset-0 v">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-barcode"></span></span>
<select class="form-control" id="deviceSelect">
<option selected disabled> <?php echo trans('areasettings.add_id_placeholder') ?> </option>
<option> TEST </option>
<?php
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
foreach ($devices as $device) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
//echo "<option value=\"$idDevice\">$idDeviceMac</option>\n";
<option value="<?= $device['id_device_mac'] ?>"><?= $device['id_device_mac'] ?></option>
}
?>
</select>
<!--<input type="text" class="form-control" placeholder="<?php echo trans('areasettings.add_id_placeholder') ?>" autocomplete="off"
ng-model="newSectionName">-->
</div>
</div>
Thanks in advance for helping me !
EDIT : Changed the fetchAll with this line (laravel way) :
$devices = DB::table('dashboard_demo.nao_device')->select('id_device_mac')->get()
But i still get the same error.
I searched deeper in my logs and also found that devices is undefined apparently.
This line looks wrong, if you are using vanilla PDO.
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
PDO::fetchAll does not execute a query, it just processes the resultset of an already executed query.
So something like this perhaps
$sql = 'select `id_device_mac` from `dashboard_demo.nao_device`';
$result = $db->query($sql);
if ( ! $result ) {
print_r($db->errorInfo())
exit;
}
while ($device = $result->fetch(PDO::FETCH_OBJ)) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
echo "<option value='$idDevice'>$idDeviceMac</option>\n";
}
This way should show you if any errors happened in the query.
Also changed the content of the while loop. You were using an array notation in there but an objct notation when getting data from the $device variable above?
I am working on displaying information from my database. When I did print_r in the model/itemTile.php below to check on my array, $this->display, I noticed it had stored 2 copies of the data from my database. I checked my database, and there was definitely only one copy of the data.
I created a counter variable, $this->counter, to see what the surrounding while loop was doing. The original data had 6 non-duplicating rows. As you may see in the jpg attached below, the program increments and echo the counter to 6, then it does the "print_r($this->display)" line that is outside of the while loop, then for some strange reason goes back to the while loop, increment the counter, and print the $this->counter and $this->display again!
I can remove the duplicate, but I would much prefer to figure out why exactly there are two copies of the value to begin with.
Since this was originally a PHP class project that focus on MVC, everything is placed into controller, model, and view. I have included the relevant model and view code below:
Jpg:
PHP Site
model/itemTile.php
<?php
require_once('siteInfo.php');
class itemTile implements siteInfo {
private $term;
private $session;
private $result;
private $display = array();
private $counter = 0;
public function __construct($session) {
$this->session = $session;
}
public function getContent() {
$this->result = $this->session->db->prepare("SELECT productName, sciName, price FROM products");
$this->result->execute();
$this->result->bind_result($pN, $sN, $pz);
while ($this->result->fetch()) {
if (array_key_exists($pN, $this->display)) {
$this->display[$pN]["price"][] = $pz;
} else {
$this->display += [
$pN => [ //Product Name was used to id array because not all item have sciName,
"sciName" => [$sN], //and not all item have only 1 sku (1 item with different size = multiple pid).
"price" => [$pz]
]
];
}
$this->counter++;
echo $this->counter . "<br />";
}
$this->result->close();
print_r($this->display);
echo "<br />";
}
public function setContent() {
$this->getContent();
return $this->display;
}
}
?>
view/itemTile.php
<?php
class itemTileView {
private $model;
public function __construct(itemTile $model) {
$this->model = $model;
}
public function output(){
foreach ($this->model->setContent() as $item => $detail) {
$itemLink = preg_replace('/\s+/','_', $item);
echo "<div class= 'tileSpace'>";
echo "<a href='itemPages/" . $itemLink. "/home.php'>";
echo "<img alt='" . $item . "' src='itemPages/" . $itemLink . "/thumbnail.jpg' width='100' height='100'>";
echo "</a>";
echo "<p>" . $item . ": " . $detail["sciName"][0] . "</p>";
if (count($detail["price"]) > 1) {
echo "<p>" . min($detail["price"]). " - " . max($detail["price"]). "</p>";
} else {
echo "<p>" . $detail["price"][0] . "</p>";
}
echo "</div>";
}
}
}
?>
Can anyone spot where is the problem occurring?
use php function array_unique();
array_unique($arrayname);
using this you will get unique values from array.it avoids duplicate values
I have this php function which looks up rows from a database table
if (!function_exists("ContactLookup")) {
function ContactLookup($column, $clause, $value, $limit1=0, $limit2=1)
{
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
while ($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs)) {
$foremame =$ContactLookup_Result["forename"];
$surname = $ContactLookup_Result["surname"];
}
}
}
This just echoes the results but if I wanted to put the results into a select element how would I do this
Within the while loop would I create the variables then echo the variables when I call the function? Or is there another way around this?
Like:
<?php ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
><select name="contactsequence" id="contactsequence">
<option value=""><?php echo $forename; ?></option>
</select
Make your function return an array
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results = [];
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = [
'forename'=> $ContactLookup_Result["forename"],
'surname'=> $ContactLookup_Result["surname"]
];
}
return $results;
}
Then you can loop through it:
<?php
$names = ContactLookup("company_sequence", "=", $result["contact"],"0","10");
echo '<select name="contactsequence" id="contactsequence">';
foreach($names AS $name){
echo '<option value="">'.$name['forename'].'</option>';
}
echo '</select>';
Change the function to return the results as a variable, rather than echo them.
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results=array();
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = array('forename'=>$ContactLookup_Result["forename"],'surname'=>$ContactLookup_Result["surname"];
}
return $results;
}
Then in your display loop,
<?php $contacts=ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
<select name="contactsequence" id="contactsequence">
foreach($contacts as $k=>$contact){?>
<option value="<?php echo $k;?>"><?php echo $contact['forename']; ?></option>
<?php
}
</select>
I cant seem to update the Phone Number, I am new to Codeigniter and been trying to figure out what I am doing wrong.
This is my MODEL:
function updatePhone($submit_userid, $submit_phone) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone
));
}
This is my CONTROLLER:
public function updateAccount() {
$this->load->model('updateModel');
$this->load->model('userModel');
$data['userdata'] = $this->session->userdata('userobject');
$this->form_validation->set_rules('phone', 'Phone', 'required|min_length[8]|max_length[12]|xss_clean');
if ($this->form_validation->run() == false) {
$this->load->view('updateView', $data);
} else {
$submit_userid = $this->input->post('userid');
$submit_phone = $this->input->post('phone');
$this->userModel->updatePhone($submit_userid, $submit_phone);
redirect('updateController/updateAccount');
}
}
This is my VIEW:
<?php
echo validation_errors();
echo form_open('updateController/updateAccount');
echo '<input type="hidden" name="userid" value=' . $userdata->intMemberID . '/> <br/>';
echo "$userdata->strMemberFirstName $userdata->strMemberLastName";
echo "<br>";
echo "Phone Number: <input type='text' name='phone' placeholder='$userdata->strPhoneNumber'/>";
echo '<INPUT type="submit" value="Update" name="submit"/>';
echo form_close();
?>
you can try this update statement, even if this doesnot works out then please check the column type you are using (varchar or whatever and its size if its conflicting or not)
<?php
$data['strPhoneNumber'] = $submit_phone;
$this->db->where('intMemberID', $submit_userid)->update('tblMembers', $data);
?>
You never perform an update to the database. The select statement is not needed in an update, you pass the table name to the update method.
function getUpdate($submit_userid, $submit_phone) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone
));
}
And you shouldn't really call the method getUpdate, it's not really semantic since you're not actually getting anything. updatePhone might be a better name.
try to print out the error
return $this->db->update("tblMembers", array );
var_dump the updatePhone result and you will see whether there is an error with table or something else
make sure it returns true before redirecting
$data = array(
"strPhoneNumber" => $submit_phone
);
$where = "intMemberID = ".$intMemberID;
//generate the query string not executing
$str = $this->db->update_string('tblMembers', $data, $where);
echo '<pre>';
echo $str;
die;
Put the above code in your function, verify the query string