I have a page were ["cart_array"] mange session to fetch total price and total quantity in the cart my problem is that am trying to foreach mysql result into ["cart_array"] as session so i can get total price and total quantity form mysql fetch result i tried:
<?php
$sqli = mysqli_query("SELECT * FROM `books` WHERE `book`='$book'");
$productCount = mysql_num_rows($sqli); // count the output amount
if($productCount 0) {
while($row = mysqli_fetch_array($sqli)){
foreach($row as $v);
}
$id = $v["item_name"];
$product_name = $v["book"];
$price = $v["quantity"];
$_SESSION["cart_array"] = array(0 => array("item_id" => $id, "quantity" => $price)); ?>
thanks in advance
$sqli = mysqli_query("SELECT * FROM `books` WHERE `book`='$book'");
$productCount = mysql_num_rows($sqli); // count the output amount
while($row = mysqli_fetch_array($sqli)){
foreach($row as $v) {
//$id = $v["item_name"]; //mybe id
$_SESSION["cart_array"][] = array(
"item_id" => $v["id"],
"quantity" => $v["quantity"],
"product_name" => $v["book"]
);
}
}
I don't now, but in your code was some loop was empty (foreach($row as $v);) and in $_SESSION["cart_array"] will be array now;
Related
This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.
I like to write a csv import / update to my Mysql database, but it isnt working. I get no error messages.
Can anybody help me to find the error or whats wrong with my script please.
// set local variables
$connect = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("shoptest1", $connect);
while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
{
$Product_ID=$data[0];
$field=$data[1];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
The queries you are performing:
SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?
are suitable to detect whether a product exists and then either UPDATE or INSERT. For only an UPDATE, the SELECT doesn't matter, as there won't be an entry WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - if you have a foreign key.
Here's an example of how to do this using PDO.
list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];
$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
] );
$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );
while ( list( $Product_ID, $field ) = fgetcsv(...) )
if ( in_array( $Product_ID, $ids ) )
query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
[ $field, $Product_ID ]
);
else
trigger_warning( "unknown product $Product_ID" );
function query( $db, $sql, $args = null ) {
$sth = $db->prepare( $sql );
$sth->execute( $sql );
return $sth;
}
Hi I am using codeigniter.I need to get the last inserted id and increment it and use it in my view page,
My controller code:
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
$insert_id = $this->billing_model->store_bill($data_to_store);
/*Here I am tring to get the last inserted id*/
for ($i = 0; $i < count($pid_array); $i++) {
if(isset($pid_array[$i])&& $pid_array[$i]!=""){
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array[$i],
'start_time' => $start_array[$i],
'pid' => $pid_array[$i],
'total' => $total_array[$i],
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
}
}
$data['ticket_new_id'] = $data_to_store['id'];
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
This is my controller function where I insert my bill.
Here is my model function,
function store_bill($data)
{
$insert = $this->db->insert('bill', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Here I am using $this->db->insert_id() to get the last inserted id.
I am getting a error like this,
You must use the "set" method to update an entry.
Filename: C:\xampp\htdocs\elfanto\elfanto_billing\system\database\DB_active_rec.php
Line Number: 1174
Can someone help me? Thanks in advance
I think this is your solution:
<?php
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
/*beore inserting first get the last ID of the table*/
$this->db->select('*');
$this->db->from('bill');
$this->db->order_by('id','desc');
$result = $this->db->get()->result();
$last_id = $result[0]->id;//This is the last ID of the table
/*now insert the data with incremented ID and send it to your view */
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array,
'start_time' => $start_array,
'pid' => $pid_array,
'total' => $total_array,
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
$insert_id = $last_id + 1;//this will be your last inserted ID
$data['ticket_new_id'] = $insert_id ;
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
For more reference how to get last ID using codeigniter check this
I have check your code not initialize the variable
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
// $data_to_store is not initialized and you are trying to store the value that's why it give you error
$insert_id = $this->billing_model->store_bill($data_to_store);
i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400
I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);
I am using the Drupal 7 Database API to search my table. I am also using the paging and sorting extenders. So the problem is, how do I display the total number of records found when my query is using limit because of the pagination? Do I need to run my query that has all of the conditions TWICE? Once to get the count and another one with the limit? That seems inefficient. Here is my code for reference. I am new to the Database API so feel free to adjust my code or point me in the right direction if I'm doing something wrong. Also I'm not done with this yet and only have one condition in place, but I will end up having 3. THANKS:
function job_search() {
// Initialising output
$output = 'SOME STUFF';
// Table header
$header = array(
array('data' => 'Description'),
array('data' => 'Location', 'field' => 'job_location_display'),
array('data' => 'Specialty', 'field' => 'specialty_description'),
array('data' => 'Job Type', 'field' => 'job_board_type'),
array('data' => 'Job Number', 'field' => 'job_number'),
);
// Setting the sort conditions
if(isset($_GET['sort']) && isset($_GET['order'])) {
// Sort it Ascending or Descending?
if($_GET['sort'] == 'asc')
$sort = 'ASC';
else
$sort = 'DESC';
// Which column will be sorted
switch($_GET['order']) {
case 'Location':
$order = 'job_location_display';
break;
case 'Specialty':
$order = 'specialty_description';
break;
case 'Job Number':
$order = 'job_number';
break;
case 'Job Type':
$order = 'job_board_type';
break;
default:
$order = 'job_number';
}
}
else {
$sort = 'ASC';
$order = 'job_number';
}
// Query object
$query = db_select("jobs", "j");
// Adding fields
$query->fields('j');
if(isset($_GET['location'])) {
$query->condition('j.job_state_code', $_GET['location'], '=');
}
// Set order by
$query->orderBy($order, $sort);
// Pagination
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
// Executing query
$result = $query->execute();
// Looping for filling the table rows
while($data = $result->fetchObject()) {
$description = '<div class="thumbnail"><img src="/sites/all/themes/zen/vista_assets/images/job_headers/' . $data->job_image_file . '"/></div>';
$description .= '<div class="title">' . $data->job_board_subtitle . '</div>';
// Adding the rows
$rows[] = array($description, $data->job_location_display, $data->specialty_description, $data->job_board_type, $data->job_number);
}
$output .= theme('pager');
// Setting the output of the field
$output .= theme_table(
array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => array('job-listing')),
'sticky' => true,
'caption' => '',
'colgroups' => array(),
'empty' => t("No records found.")
)
).theme('pager');
// Returning the output
return $output;
}
This ended up working:
//get total records
$num_rows = $query->countQuery()->execute()->fetchField();
// add paging and sorting
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
//execute again
$result = $query->execute();
According to the documentation:https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7
in order to get the total number of rows it is better to use db_query() function, cause it has the method rowCount() which returns total number of query rows:
<?php
// Using the same query from above...
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Fetch next row as a stdClass object.
$record = $result->fetchObject();
// Fetch next row as an associative array.
$record = $result->fetchAssoc();
// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);
// Count the number of rows
$result->rowCount();
?>