How to insert data from a database to array and check it - mysql

I need to modify views in an application and I have table user privileges, with a structure like this below
id_staff | feature | capabilities
1 reports view
1 reports create
1 reports edit
2 reports view
2 reports delete
3 reports view
What I need, is where user like id_staff 3 that in reports, feature only have one capabilities, like the example he just can view, can not edit, edit, or create. Then user id 3 only sees hyperlink to view the page, he cannot see hyperlink to create, edit or delete pages.
To do that, I tried to use select query, insert that to array and then compare the array value to getting the condition like above
I have tried to code like this
<?php
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result() as $row)
{
if($row['feature']=='reports' and $row['capabilities']=='view'){
View
} elseif($row['feature']=='reports' and $row['capabilities']=='delete' ){
Delete
}
}
?>
And then the page is blank
Do you know where's the error ?
Thank you

You could improve it by reducing the repetitive code, like the $row['feature']=='reports' code, like :
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result_array() as $row)
{
if ($row['feature']=='reports') {
if ($row['capabilities']=='view') {
echo 'View';
} elseif ($row['capabilities']=='delete') {
echo 'Delete';
}
}
}
To get an array result, use the $query->result_array() instead of $query->result(), and also you misses the echo statement.

You are using $query->result() it will give you an array of objects, not an array of array. Also, you are not echoing your links on the view. One more thing you should not use the same condition repeatedly.
In this case, your code should be -
<?php
$query = $this->db->query('SELECT * FROM tblstaff_permissions WHERE staff_id='.$id.'');
foreach ($query->result() as $row) {
if($row->feature =='reports'){
if($row->capabilities=='view'){
echo 'View';
} elseif($row->capabilities == 'delete' ){
echo 'Delete';
}
}
}
?>

Related

MYSQL How can I make dropdown list?

I created a new table in workbench where I want to put a season of a soccer championship.
I don't want to write down every time the team's names, can you help me pls, how can I make like a dropdown list (or set of values, what are the only options for that column), when I begin to type "Bay..." its automatically offer "Bayern München" as the only option.
I don't know how much will this help, but I have made a dropdown list for something else and I hope my way might give you an idea:
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
if($row[id]==10)
{
echo "<option value=$row[id] selected>$row[name]</option>";
}
else
{
echo "<option value=$row[id]>$row[name]</option>";
}
}
echo "</select>"; // Closing of list box
As the same answer above, but using short-hand ternary operator instead of if-else statement, and don't forget to use ' or " when reference to object string index.
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
printf("<option value='%s' %s>%s</option>", $row['id'], $row['id'] == 10 ? 'selected' : '', $row['name']);
}
}
echo "</select>"; // Closing of list box

How can I load two different set of datas to a dynamic dependent drop down?

Actually I am using two dropdowns where first dropdown selects 'Department' and once the department is loaded in the first dropdown, employees in the relevant department loads in the second.
It works fine. But what i need now is I need to load employees of the currently logged in users department and Other department heads in the second dropdown. How can I query this in CodeIgniter Model. This is my table in database
This is my Table:-
My table to query:-
Here when I select 'Admin" [Say Admin Head is logged in] Department I need to
select all 'user_level = 2' and 'user_dept = Admin' and with this I need to include all other 'user_level = 3'
Like wise i need to show logged in users department employees and other departments heads only in second dropdown.
My AJAX from View through controller successfully returns the query that i wrote in model.
But i need help to query the specific thing that I needed in CodeIgniter query.
This is my Model funtion which only returns user_level = 3
function fetch_dept_officers_for_forward($Dept) //for forward by dHead
{
//echo "Test";
echo $this->session->userdata('udept');
$this->db->where('user_dept',$Dept);
//$this->db->where('user_level','3');
$this->db->or_where('user_level','3');
$this->db->order_by('user_name', 'ASC');
$query = $this->db->get('tbl_users');
$output = '<option value="">Select Officer</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->user_name.'">'.$row->user_name.'</option>';
}
return $output;
}

Save SQL result to variable

Is it possible to save SQL result in variable and then use that to echo data anywhere on my site.
for example
$result=mysqli_query("SELECT * FROM table");
and then use that variable to show that data anywhere else on site and even repeat it in some loop
$show=mysqli_fetch_assoc($result)
I tried that in for while loop and it echo my result only once.
my full code
$result=mysqli_query("SELECT * FROM table");
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
while( $show=mysqli_fetch_assoc($result))
{echo $show["ID"];}
}
Make a $table1_array and a $table2_array and instead of echo $x use $table1_array[] = $x. Since the table2 - select needs nothing from table1 you should read it only once. Make no inner loop, make two separate loops.
EDIT:
to clarify:
$result=mysqli_query("SELECT * FROM table");
$table_array = array();
while( $show=mysqli_fetch_assoc($result)){
$table_array[] = $show;
}
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
foreach($table_array as $show){
echo $show["ID"];
}
}

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num