PHP loop stops unexpectly - php

I have a table (table3) in MYSQL with 99 text fields (field1, filed2, ...,field99). I wanted to count the non-empty values of each field so I wrote a simple php script with a for loop as below:
for($i = 1; $i <= 99; $i++)
{
$sqlstm = "SELECT COUNT(field$i) FROM table3 WHERE field$i IS NOT NULL AND field$i <> '';";
$r = #mysqli_query($dbc, $sqlstm);
if($r)
{
while($row = #mysqli_fetch_array($r))
{
echo "<p>$row[0]</p>\n";
}
}
else
{
echo "field $i error: " . mysqli_error($dbc);
}
}
But the loop stopped after showing four values (field1 to filed4) and no error message. I do have all 99 fields with data in table3 and I could run the query manually for any field. Could this due to browser timeout?
Can someone help me? Thanks.

$sqlstm = "SELECT COUNT(field$i) FROM table3
you are selecting the columns here, your table has 99 rows but apperantly only 4 columns
what you could better do is
$sqlstm = "SELECT * FROM table3 WHERE (column name) IS NOT NULL";
$count = 0
for($sqlstm as $one) {
$count = $count + 1;
}
echo($count);
or something along those lines

Related

How to add dynamic counter for insert sql

I would like to add a counter to show sequence of record inserted per query.
if(isset($_POST['keyword'])){
$keyword = $_POST['keyword'];
if($keyword){
foreach($keyword as $row){
$keyword_exe = $con->prepare("
INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '???')
");
$keyword_exe->execute();
}
}
}
I expect the output will be like this:
I didnt test with INSERT but you can use this when you SELECT
ROW_NUMBER() OVER(PARTITION BY m_id ORDER BY id ASC) sequence_counter
For save some database space
More here
$counter = 0;
$pre_row = 0;
foreach($keyword as $row){
if( $pre_row == $id){
//In row m_id value equal to next value increase counter by 1
$counter++;
}else{
//else start to 1
$counter = 1;
$pre_row = $id;
}
$keyword_exe = $con->prepare("
INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '$counter')
");
$keyword_exe->execute();
}
DEMO

how to update column without using auto_increment value with 001 to so on

This is my table with name and unique numberenter image description here
This is my PHP code
$id = explode(",", $params["txtID"]);
for ($i = 0; $i <count($id); $i++) {
$sql = "SELECT 'auto_increment' as LastID FROM
INFORMATION_SCHEMA.TABLES WHERE table_name = 'esi_master' ";
$result = $this->con->query($sql);
if (intval($result->rowCount($result)) > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$lclId = intval($row["LastID"]) - 1 + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
} else {
$lclId = intval($row["LastID"]) + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
$sql = $this->con->prepare("UPDATE esi_master SET esi_status = 1,
esi_dcno = '$lclDcno[$i]' Where esi_id = '$id[$i]'");
echo $result = $sql->execute();
}
Here First I insert Names to the table using Insert Statements and next for some operation I update the Unique number unique number should start updating from the empty row, update done with unique id, The txtID contains ID`s like 1, 2, 3, 4 so on as I select table row in front end, in that basis that updates.Thanks in Advance.
You need another field to save, with type varchar(10).
data will not be able to save into integer(auto_increment)

PHP Insert multiple rows in split batches

I have a query to insert multiple rows in split batches. Basically, I need to split inserts in batches so that I can generate a unique random ID to the inserted batch.
What I've tried and failed with many different options, one of them as follow.
$batch = 150;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++){
$columns1 = $results[$i]['column'];
if($i==$batch){
$randd = randcode(5).time();
$sql = "INSERT INTO `newtable` SET `columns1` = ".$con->qstr($columns1).", `rcode` = ".$con->qstr($randd).", `DATE_PUBLISHED` = ".$con->qstr($sdate);
$results=$con->Execute($sql);
$i=0;
}
}
However, am not successful in inserting unique code to every 150 batch inserted query.
Where am I going wrong in generating random unique code for every batch? And also I would like to know if there is less than 150 records, then how to handle the same?
This will provide you with the logic for a basic way for setting a random ID per batch.
In this example, there is no database connectivity. You will have to add that yourself. You also want to have a look at the syntax for the INSERT statement (spoiler: INSERT INTO <table name> (<columns>) VALUES (<values>)).
// For this example, generate a result array with 350 rows
// (remove when using actual db query)
for ($i = 1; $i <= 350; $i++) {
$results[] = ['column' => 'column ' . $i];
}
// Loop through all result rows
foreach ($results as $batchCounter => $result) {
if ($batchCounter % 150 == 0) {
// Generate a new random ID for the first row and every 150 rows
$random = uniqid();
}
// Replace with proper insert statement
echo "Insert random ", $random, ' for column "', $result['column'], '"', PHP_EOL;
}
Output:
Insert random 55e0186b0607f for column "column 1"
Insert random 55e0186b0607f for column "column 2"
Insert random 55e0186b0607f for column "column 3"
...
Insert random 55e0186b0607f for column "column 150"
Insert random 55e0186b063da for column "column 151"
Insert random 55e0186b063da for column "column 152"
Insert random 55e0186b063da for column "column 153"
...
Insert random 55e0186b063da for column "column 300"
Insert random 55e0186b0666e for column "column 301"
Insert random 55e0186b0666e for column "column 302"
Insert random 55e0186b0666e for column "column 303"
...
Insert random 55e0186b0666e for column "column 350"
You have to try this one
<?php
$batch = 0;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
$sql = "";
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==0)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
if($batch==150)
{
$results=$con->Execute($sql);
$batch=0;
$sql="";
}
$batch++;
}
You have to try this one. I fixed some errors from your code to insert records successfully:
<?php
$batch = 1;
$rows = 0;
$sql = "";
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==1)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
$rows++;
if($batch==100)
{
$this->SendRecords($conn, $sql);
$batch=1;
$sql="";
} else if($rows == count($results) && $batch > 1 && $batch<=100){
$this->SendRecords($conn, $sql);
$batch=0;
$sql="";
}else {
$batch++;
$sql.=",";
}
}

Fetching data from relational database in codeigniter

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal
$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

Multiple Mysqli Select Statement, echo separated results

I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco

Categories