Mysqli Insert Inside While Loop and For loop - arrays

I am stuck in this code, the problem is that I am trying to insert values inside the while loop and For loop, I have 584 Records and i need to insert 15 records into another table
<?PHP
$payroll_date = '2020-01-15';
$date_from = '2019-12-21';
$date_to = '2020-01-05';
$query = "SELECT * FROM adb_crosschex GROUP BY userid";
$result = mysqli_query($db, $query);
if ($result)
{
$row = mysqli_num_rows($result);
/* ######################################################################### */
$x = 0;
$sqltoDTR = "SELECT * FROM adb_crosschex GROUP BY userid";
$dtrResult = mysqli_query($db, $sqltoDTR);
while($rows = mysqli_fetch_array($dtrResult))
{
$x++;
$begin = new DateTime($date_from);
$end = new DateTime($date_to);
$pay_period = date("m-d", strtotime($date_from))." - ".date("m-d", strtotime($date_to));
$idcode = $rows['idcode'];
$controlno = $rows['userid'];
$acctname = $rows['acctname'];
$transdate = $rows['transdate'];
$branch = $rows['branch'];
for($i = $begin; $i <= $end; $i->modify('+1 day')) {
$date_trans = $i->format("Y-m-d");
/* result
2019-12-21
2019-12-22
2019-12-23
2019-12-24
....... until reaching the $end
*/
/* mysql Insert goes here */
}
}
/* ######################################################################### */
mysqli_free_result($result);
}
mysqli_close($db);
?>
the problem with the code is that it inserted data like forever i tried to leave it for 30 minutes and i get like 1 Million plus into my table hahahaha I supposed to get 584 x 15 = 8760 records Please Help

Ok i think i solve it for the code
for($i = $begin; $i <= $end; $i->modify('+1 day')) {
$date_trans = $i->format("Y-m-d");
myQuery($idcode, $payroll_date, $pay_period, $branch, $controlno, $date_trans, $acctname);
}
i try to put the insert query outside the loop and it goes like this
function myQuery($idcode, $payroll_date, $pay_period, $branch, $controlno, $date_trans, $acctname)
{
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$sql = "INSERT INTO `tbl_dtr`(idcode,payroll_date,pay_period,branch,controlno,date_trans,acctname)VALUES('$idcode', '$payroll_date', '$pay_period', '$branch', '$controlno', '$date_trans','$acctname')";
if ($db->query($sql) === TRUE) { echo "-<br>"; } else { echo $db->error; }
}

Related

How can i get top 15 occurrences in an array and use each value to fetch data from mysql database?

I am currently working on a project (A music website) with PHP Codeigniter. I want to fetch top 15 songs by number of downloads. To my knowledge, I got all unique ID's out ranging from highest to least. But now, I want to use each of these unique ID's to fetch data from another table in the database.
I have tried using for loop; but it seems to only return one of the rows which happens to be the first and highest number of occurrence in the array. The code below echo's the ID's but how can I use each of those ID's to fetch data.
function top15(){
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row)
{
$musiccode[] = $row['musiccode'];
}
$mode = array_count_values($musiccode);
arsort($mode);
$i = 0;
foreach ($mode as $field => $number) {
$i++;
echo $field." occured ". $number." times <br>";
if ($i == 15) {
break;
}
}
}
}
for ($b=0; $b < count($field); $b++) {
$this->db->where(array('track_musiccode'=> $field));
$field = $this->db->get('tracks');
return $field->result_array();
}
The code above only produce one row for me. I expect to have more than one and according to the number of ID's in the array. Thanks in advance.
For a single column condition, you could use where_in() instead and drop the for loop :
$this->db->where_in('track_musiccode', $field);
$field = $this->db->get('tracks');
return $field->result_array();
Yes Finally i did it. Incase if anyone needs it. this works just fine
function top15(){
$this->db->where('d_month', date('m'));
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row){
$musiccode[] = $row['musiccode'];
}
$res='';
$count=array_count_values($musiccode);
arsort($count);
$keys=array_keys($count);
for ($i=0; $i < count($keys); $i++) {
$res[] .= "$keys[$i]";
}
$this->db->where_in('track_musiccode', $res);
return $this->db->get('tracks')->result_array();
}
}
And I got this too. If I wasn't going to count occurrences but just iterate the number of downloads which is far more better than counting in other not to over populate the database and make your website work slowly.
function top15(){
$tracks = '';
$this->db->group_by('counter');
$result=$this->db->get('downloads');
$query = $result->result_array();
$counter = '';
$fields = '';
if(!empty($query)) {
foreach($query as $row) {
$counter[] = $row['counter'];
}
rsort($counter);
for ($i=0; $i<=15; $i++) {
$this->db->where('downloads.counter', $counter[$i]);
$this->db->join('tracks', 'tracks.musicid = downloads.musicid');
$fields[] = $this->db->get('downloads')->row_array();
}
return $fields;
}
}
Enjoy...

sum values from db with array_sum() stuck at 3 loop

after couple of days i finally got some values from 1st and 2nd line but after that at 4th line i got stacked and nothing works.
in need to get data from db where:
obrat | memb | tab3. | history
| member1 | 0. | 10
200 | member2 | member1. | 3
100 | member3 | member1. | 4
so if i will select from tab3 users which have my memb i need to sum their obrat and history. And doo the same think with them - select from tab3 where names are member1 and member2 and sum that.
my code:
while ($row = $resulto->fetch_assoc()) {
$memb2 = $row['memb'];
// second line member sel.
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
//pokud druhá linie
if ($resulto2->num_rows > 0) {
while ($row2 = $resulto2->fetch_assoc()) {
$memb3 = $row2['memb'];
} // should be 3. line
// get numbers from 2. line
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
$d = 0;
$rows2 = array();
$rows3c = array();
while ($rowd = $resulto2->fetch_array()) {
array_push($rows2, $rowd['obrat']);
array_push($rows3c, $rowd['history']);
}
$array2 = array_sum($rows2);
$count3 = array_sum($rows3c);
}
}
//end / get values first line
$resulto = $mysqli->query("SELECT * FROM users WHERE tab3='$memb' ") or die($mysqli->error());
$d = 0;
$rows = array();
$rows2c = array();
while ($rowd = $resulto->fetch_array()) {
array_push($rows, $rowd['obrat']);
array_push($rows2c, $rowd['history']);
}
$array = array_sum($rows);
$count2 = array_sum($rows2c);
}
some idea where is the problem?
or next way iam trying to :
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb' ") or die($mysqli->error());
if ($resulto2->num_rows > 0) {
while ($row2 = $resulto2->fetch_assoc()) {
$memb2 = $row2['memb'];
$resulto2a = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
while ($row2a = $resulto2a->fetch_assoc()) {
$memb3 = " OR memb='".$row2a['memb']."'";
//here i need to get one value which is sum from all users selecting
}
}

How do i return an error statement if the query is empty?

I would like echo something if the query is empty.
session_start();
include 'inc/db.php';
$student_id = $_POST['username'];
$password = $_POST['password'];
if($stmt = $conn->prepare("SELECT p.parent_id, ps.student_id, p.password
FROM parent p,
parentstudent ps
WHERE p.parent_id = ps.parent_id
AND student_id = ? limit 1")) {
$stmt->bind_param("s", $student_id);
$stmt->execute();
$stmt->bind_result($id, $student_id, $bindpassword);
while ($stmt->fetch()) {
if(password_verify($password, $bindpassword)){
$_SESSION['parent_id']= $id;
$_SESSION['student_id'] = $student_id;
header("location: parent.php");
}
else
echo "The student ID or password you have entered is inccorrect";
}
}
$stmt->close();
since you got only one row to retrieve from the database you could just replace the while with an if (i've deleted my previous response)
session_start();
include 'inc/db.php';
$student_id = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT p.parent_id, ps.student_id, p.password
FROM parent p,
parentstudent ps
WHERE p.parent_id = ps.parent_id
AND student_id = ? limit 1") ;
$stmt->bind_param("i", $student_id);
$stmt->bind_result($id, $student_id, $bindpassword);
$stmt->execute();
if($stmt->fetch()) {
if(password_verify($password, $bindpassword)){
$_SESSION['parent_id']= $id;
$_SESSION['student_id'] = $student_id;
header("location: parent.php");
}
else {
echo "The student ID or password you have entered is inccorrect";
}
}
else {
echo "nothing was fetch";
}
$stmt->close();
I've put two else, one if the password is incorrect, and one if there was no fetchs in the database

Which of Database::<QUERY_TYPE> I should use in Kohana 3.3?

I need perform query "LOCK TABLE myTable WRITE"
<?php
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(Database::WHAT_IS_THE_TYPE_SHOULD_SPECIFY_HERE_?, $query);
In framework Kohana 3.3
file ~/modules/database/classes/Kohana/Database.php
implements folowing types:
const SELECT = 1;
const INSERT = 2;
const UPDATE = 3;
const DELETE = 4;
but none of them fit in my case.
Any idea. Thanks.
Google works wonders. http://forum.kohanaframework.org/discussion/6401/lockunlock/p1
You can pass NULL as the first argument:
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(NULL, $query);
From Kohana: http://kohanaframework.org/3.3/guide-api/Database_MySQL#query
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
As you can see that's why you're able to pass NULL.

How to return value of 2 data in foreach which each data has 5 rows in model of codeigniter to view

I have a similar problem that the function only return the first loop data.
The result should be 2 loops and each loop has rows data.
For example, The first loop is A and has 5 rows data and second loop is B and has 5 rows.
The return value only A with 5 rows, it sould be 10 rows. 5 rows A + 5 rows B.
How is the code should be?
This function in model is bellow
function getDataForm($data_search)
{
$i=0;
if(!empty($data_search['arr_idacl']))
{
foreach($data_search['arr_idacl'] as $idx => $val)
{
if(!empty($operatingHour))
{
$sql = "SELECT be_acl_resources.description as description,DATE_FORMAT(tbl_camera_detail.start_time,'%d %M %Y ') as datadate, SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters*(-1),0))+SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits*(-1),0)) as total_enter FROM tbl_consolid JOIN tbl_consolid_detail ON tbl_consolid.id = tbl_consolid_detail.consolid_id JOIN tbl_config_data ON tbl_consolid_detail.config_data_id = tbl_config_data.id JOIN tbl_camera ON tbl_config_data.id_acl = tbl_camera.id_acl JOIN tbl_camera_detail ON tbl_camera.id = tbl_camera_detail.camera_id JOIN be_acl_resources ON tbl_consolid.id_acl = be_acl_resources.id WHERE tbl_camera.date >= '".$data_search['start_date']."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') >= '".$startOpratingHour."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') <= '".$operatingHour['finish_time']."' AND tbl_camera.date <= '".$data_search['end_date']."' AND tbl_consolid.id_acl = '".$val."' GROUP BY tbl_camera.date";
echo $sql;
$query = $this->db->query($sql);
$result_data[] = $query->result();
//return $result;
}
$i++;
}
return $result_data;
}
}
Declare $result_data = array(); just before if(!empty($data_search['arr_idacl'])) condition.
Replace $result_data[] = $query->result(); with $result_data[$i] = $query->result();
Update:
Just close to the answer. :) Try this:
Replace $result_data[] = $query->result(); with $result_data[$i][] = $query->result();

Resources