I want to delete top first row from table in firebase Database when no. of rows reach to 50.
I can search this lot of time but still not found. Anyone tell that how I can do this.
Through this technique
$searchdata = "Data";
$fetchdata = $database->getReference($searchdata)->getValue();
$found = 0;
$array=0;
if($fetchdata > 0)
{
foreach($fetchdata as $Key => $row)
{
if($found == 0)
{
$del = "Data/".$Key;
$DelRef = $database->getReference($del)->remove();
$found=1;
}
else
{
break;
}
}
}
Related
I am having issue data Array overwritten in foreach loop. Result I am getting like this wrongRight together .Right answer is showing but also wrong for example ZucchiniCauliflower.Please help
CODE 1
$data = array();
$dis_07= null;
$dis_03 = null;
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id = $value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$dis_07 = $value->category;
$dis_02 = $value->child_id;
}
if (isset($ccat_id) && $ccat_id == $id) {
$dis_03 = $value->category;
$dis_02 = $value->parent_id;
}
}
}
$data['Dis_03'] = $dis_03;
$data['Dis_07'] = $dis_07;
if (isset($data['Dis_03'])) {
echo $data['Dis_03'];
}
if (isset($data['Dis_07'])) {
echo $data['Dis_07'];
}
First I tried this way But In one I was getting right in second link I am getting right So Tried the code previous one .In the prvious I am getting correct and wrong one together EExample ZucchiniCauliflower
CODE 2
if (isset($id)) {
$db = Database::newInstance();
$data = array();
$data['cat_status'] = 1;
$sql = "SELECT * FROM category WHERE cat_status=:cat_status ";
$row = $db->read($sql,$data);
$data['id'] = $crypt->decryptId($id);
echo $data['id'];
$id=$data['id'];
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id=$value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$data['Dis_03']=$value->category;
}
if (isset($ccat_id) && $ccat_id == $id) {
$data['Dis_03'] = $value->category;
break;
}
}
}
}
--------------------------READ FROM HERE------------------------
Here is a link one when I click on this link
$id=$value11->gccat_id;
$title
I expected the output is
Home>Raspberry
Here is a link Second link when I click on this link
Here id is ($value11->gccat_id)
window.open('<?= BASEURL ?>ap/'+id,'_self');
I expected the output is
Home>Cauliflower
1. WHEN I Use the Code 2 (Added break in this condition
(isset($ccat_id) && $ccat_id == $id)) Then click on link second
it gives output Home>Cauliflower which I was expecting. It is
correct.
2. But this time as I added the break in (isset($ccat_id) && $ccat_id == $id). I click on link one It gives wrong output which I was not expecting. Home>Squash which is wrong.
In one link I was expecting
Home>Cauliflower
ERROR NOTE If I add Break; then link Second gives correct output but when I remove Break; then link one give correct. I wanted Both link should give correct output.
Problem was with cat_id,ccat_id ,gccat_id.
I provided 8 digit unique number with the following output,now I am getting the correct output.
function generateUniqueNumber() {
return sprintf('%08d', mt_rand(1, 99999999));
}
I have a script that imports records to multiple database tables, all relation to one parent entity (address).
If the address already exist, extra columns should just be updated according to the csv. The same counts for all other entities. A counter ($exist++) should increase or an array ($existingRecords) should be filled with already existing records.
If mandatory fields are empty in the record, that record should be added to another array ($failedRecords) or another counter ($failed++) should increase.
If the address doesn't yet exist and should be created with all fields just a counter ($successful++) should increase.
In the end I have an array $result that give the number of failed, successful, and already existing (but updated) records, for user feedback.
How can I implement this in a nice clean manner without messing my current script too much up? Because what is happening right now, if a record already exist the $exist counter increase but the $successful counter as well, and I only want the $exist counter to increase if a record already already exists, and only the $successful counter should increase if a record still has to be added and was added successfully. Same goes for the $failed counter.
Here is my script (with what I tried):
public function import(CsvFile $csv) {
$root = __DIR__.'/../../../../../';
$file = $root.'var/data/'.$csv->getCsvName();
$fp = fopen($file, "r");
$batchSize = 25;
$header = null;
$successful = 0;
$failed = 0;
$exist = 0;
$results = [];
while ($row = fgetcsv($fp, null, ";")) {
if ($header === null) {
$header = $row;
continue;
}
$record = array_combine($header, $row);
// cast all values to correct data types
foreach ($record as $key => &$value) {
if (strpos($key, 'datum') !== false ||
strpos($key, 'tijdstip') !== false &&
strlen($value) == 8 &&
is_numeric($value)
) {
$value = \DateTime::createFromFormat('Ymd', $value);
}
if ($value === "") {
$value = null;
}
if (is_numeric($value)) {
intval($value) == $value ? $value = (int)$value : $value = (float)$value;
}
}
// required fields
if (!$record['name'] ||
!$record['surname'] ||
!$record['email'] ||
!$record['phone'] ||
!$record['street'] ||
!$record['houseNo'] ||
!$record['town'] ||
!$record['postcode'] ||
!$record['location'] ||
!$record['lecture'] ||
!$record['session'] ||
) {
$failed++;
continue;
}
$student = $this->em->getRepository(Student::class)->findStudent(
$record['name'], $record['surname'],
$record['email'], $record['phone']
);
if (!$student) {
$student = new Student();
$student->setName($record['name']);
$student->setSurname($record['surname']);
$student->setEmail($record['email']);
$student->setPhone($record['phone']);
} else {
$exist++;
}
$student->setAge($record['age']);
$student->setLength($record['length']);
$address = $this->em->getRepository(Address::class)->findOneBy([
'street' => $record['street'],
'houseNo' => $record['houseNo'],
'town' => $record['town'],
'postcode' => $record['postcode'],
);
if (!$address) {
$address = new Address();
$address->setStreet($record['street']);
$address->setHouseNo($record['houseNo']);
$address->setPostcode($record['postcode']);
$address->setTown($record['town']);
}
$student->setAddress($address);
$lecture = $this->em->getRepository(Lecture::class)->findOneBy([
'location' => $record['location'],
'lecture' => $record['lecture'],
'session' => $record['session'],
]);
if (!$lecture) {
$lecture = new Lecture();
$lecture->setLocation($record['location']);
$lecture->setLecture($record['lecture']);
$lecture->setSession($record['session']);
}
$lecture->setTime($record['time']);
$lecture->setSubject($record['subject']);
$student->setLecture($lecture);
$validationErrors = $this->validator->validate($student);
if (!count($validationErrors)) {
$this->em->persist($student);
$successful++;
}
if (($successful % $batchSize) == 0) {
$this->em->flush();
}
}
fclose($fp);
$csv->setImported(true);
$this->em->persist($csv);
$this->em->flush(); // Also persist objects that did not make up an entire batch
$results['successful'] = $successful;
$results['failed'] = $failed;
$results['exist'] = $exist;
return $results;
}
You can replace the existing records counter with a flag that is set to TRUE only if the current record is an existing one, and use it at the end before persisting the record.
You can set the flag to FALSE on the beginning of each loop:
while ($row = fgetcsv($fp, null, ";")) {
$existingRecordFlag = FALSE; // initialize the flag for the current record
then update it instead of the counter :
if (!$student) {
$student = new Student();
$student->setName($record['name']);
$student->setSurname($record['surname']);
$student->setEmail($record['email']);
$student->setPhone($record['phone']);
} else {
$existingRecordFlag = TRUE; //update the flag
}
then before persisting user check the value for the flag and according to it update the counter:
$validationErrors = $this->validator->validate($student);
if (!count($validationErrors)) {
$this->em->persist($student);
if ( !$existingRecordFlag){
$successful++; //new record
}else{
$exist++; //existing user
}
}else{
$failed++; //failed as the validations has errors
continue;
}
also you can add the existing records to the batch counter as they might be updated, they can also be persisted with the successful ones
if ((($successful+$exist) % $batchSize) == 0) {
$this->em->flush();
}
In your block handling the addresses you could an existing/failed counter quite easily:
$exist++;
if (!$address) {
$exist--;
$successful++;
//...
}
This will always increase the exist-counter, but jump back if address is empty and increase the new address-counter instead. Alternatively you could work with array_push($record) and array_pop($record) to add/remove the current record from a list. This might cause memory issues, since you keep your records in multiple arrays and you might run into out of memory errors.
For missing mandatory fields you'd have to do a check on the $address afterwards to see if it's not empty/containing invalid data and then increase the counter/update the field.
If you want
I am creating a mini search engine for my new poll application. When you go to http://www.pollmc.com/search.php?s=mlg (website not up yet btw) it will search for a similar poll (I have a demo one called "Mlg Right?". It doesn't return it... But If I type in "Right" it does. It returns two polls; one called "Mlg Right?" and the other called "Cool Right?". What percent parameter is recommended for the is_similar text function? Here's my current code:
function search($s, $highPriority = true) {
$link = $this->connect();
$results = array();
$results_highpriority = array();
$results_lowpriority = array();
$query = mysqli_query($link, "SELECT * FROM polls");
while($row = mysqli_fetch_array($query)) {
array_push($results, $row);
}
foreach($results as $r) {
if(strtolower($r['question']) == strtolower($s)) {
array_push($results_highpriority, $r['question']);
continue;
}
/*if(strlen($s) >= 3 && strpos(strtolower($r['question']), strtolower($s)) !== false) {
array_push($results_lowpriority, $r['question']);
continue;
}*/
similar_text(strtolower($r['question']), strtolower($s), $resultPercent);
if($resultPercent >= 50) {
array_push($results_lowpriority, $r['question']);
continue;
}
}
return $highPriority ? $results_highpriority : $results_lowpriority;
}
I did have - commented out - if the question from MYSQL contains the query then add it (that seemed to work) but I'm worried it will return too much when I have like 20+ polls added. Here's my SQL database: http://prntscr.com/alr811
Before I begin, I want to point out that I can solve my problem. I've rehearsed enough in PHP to be able to get a workaround to what I'm trying to do. However I want to make it modular; without going too much into detail to further confuse my problem, I will simplify what I am trying to do so that way it does not detract from the purpose of what I'm doing. Keep that in mind.
I am developing a simple CMS to manage a user database and edit their information. It features pagination (which works), and a button to the left that you click to open up a form to edit their information and submit it to the database (which also works).
What does not work is displaying each row from MySQL in a table using a very basic script which I won't get into too much detail on how it works. But it basically does a database query with this:
SELECT * FROM users OFFSET (insert offset here) LIMIT (insert limit here)
Essentially, with pagination, it tells what number to offset, and the limit is how many users to display per page. These are set, defined, and tested to be accurate and they do work. However, I am not too familiar how to handle these results.
Here is an example query on page 2 for this CMS:
SELECT * FROM users OFFSET 10 LIMIT 10
This should return 10 rows, 10 users down in the database. And it does, when I try this command in command prompt, it gives me what I need:
But when I try to handle this data in PHP like this:
<?php
while ($row = $db->query($pagination->get_content(), "row")) {
print_r($row);
}
?>
$db->query method is:
public function query($sql, $type = "assoc") {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
if ($type == "row") {
return mysql_fetch_row($result);
} elseif ($type == "assoc" || true) {
return mysql_fetch_assoc($result);
} elseif ($type == "array") {
return mysql_fetch_array($result);
} elseif ($type == false) {
return $result;
}
}
$pagination->get_content method is:
public function get_content() {
global $db;
$query = $this->base_sql;
if (!isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"]) && $_GET["page"] == 1) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
$query .= " OFFSET " . (($_GET["page"] * $this->default_limit) - 10);
return $query;
}
}
And my results from the while loop (which should print out each row of the database, no?) gives me the same row everytime, continuously until PHP hits the memory limit/timeout limit.
Forgive me if its something simple. I rarely ever handle database data in this manner. What I want it to do is show the 10 users I requested. Feel free to ask any questions.
AFTER SOME COMMENTS, I'VE DECIDED TO SWITCH TO MYSQLI FUNCTIONS AND IT WORKS
// performs a query, does a number of actions dependant on $type
public function query($sql, $type = false) {
$sql = $this->escape($sql);
if ($result = $this->db->query($sql)) {
if ($type == false) {
return $result;
} elseif ($type == true || "assoc") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_assoc()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_assoc();
}
} elseif ($type == "array") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_array()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_array();
}
}
} else {
die("There was an error running the query, throwing error: " . $this->db->error);
}
}
Basically, in short, I took my entire database, deleted it, and remade another one based on the OOD mysqli (using the class mysqli) and reformatted it into a class that extends mysqli. A better look at the full script can be found here:
http://pastebin.com/Bc00hESn
And yes, it does what I want it to. It queries multiple rows, and I can handle them however I wish using the very same methods I planned to do them in. Thank you for the help.
I think you should be using mysql_fetch_assoc():
<?php
while ($row = $db->query($pagination->get_content())) {
print_r($row);
}
?>
I am trying to get a count of active users and unactive users.
First i get all user data:
$userData = fetchAllUsers();
Then I write a foreach to get a total of the users who are active and the users who are unactive.
foreach ($userData as $key => $value) {
$active = $value['active'];
if($active == 1){
$activeUsers = count($active);
print_r($activeUsers);
} elseif($active == 0) {
$unactiveUsers = count($active);
print_r($unactiveUsers);
}
}
All this prints is 1111111. There are 5 users set to 1 (active) and 2 users set to 0 (unactive) in the database. So I am looking to add these up to be 5 active and 2 unactive.
I have triedcount and array_sum and array_count_values. Nothing seems to be doing what I need. Any help would be appreciate. Can someone guide me in the right direction?
You're inside a loop, you don't need count. Just increment a counter yourself. And wait until you're done with your loop to spit out the results.
$activeUsers = 0;
$inactiveUsers = 0;
foreach ($userData as $key => $value) {
$active = $value['active'];
if($active == 1){
$activeUsers++;
} elseif ($active == 0) {
$inactiveUsers++;
}
}
var_dump($activeUsers);
var_dump($inactiveUsers);
You need to count up a variable, e.g.
$active = 0;
$inactive = 0;
foreach ($userData as $key => $value) {
switch(true) {
case $value['active'] == 1: $active++; break;
default: $inactive++; break;
}
}
var_dump("Active users" + $active);
var_dump("Inactive users" + $inactive);