Show if propel successfully deleted related data - php

I have something like this
$table = TableQuery::create()
->findOneByTableId(1);
foreach($table->getSomeTables() as $item) { // SomeTable is a table linked with foreign-key
$table->removeSomeTable($item);
}
if($table->save()) {
echo "success";
}else {
echo "fail";
}
The problem here is that despite the $table having someTablesScheduledForDeletion and successfully removing it from database when calling method save(), save still returns 0, as if "0 records were changed", though some records are actually deleted.
The same thing goes if I attach more things in a similar way as I did with someTables
What I want to achieve with this is to just get information if these elements were successfully removed

You should just call ->delete() on $item, then you can use ->isDeleted() as intended.
For example:
$table = TableQuery::create()->findOneByTableId(1);
$deleted = 0;
foreach ($table->getSomeTables() as $item) {
$item->delete();
if ($item->isDeleted()) {
$deleted++;
}
}
if ($deleted > 0) {
echo "Rows deleted.";
} else {
echo "No rows deleted.";
}

Issuing another query may be useful. Is there some reason to avoid this?

Related

executing if condition after a function called in else part. Why?

I am checking data if its not exist than insert. so i am using if else condition.
take a glance on code.
if($_POST['save_appointment']){
if(is_user_logged_in()){
$user_appontment_sql = "select * from ".$wpdb->prefix."table where status=1 AND event_id=1 AND user_id=2";
$get_user_data_row = $wpdb->get_row($user_appontment_sql);
if(isset($get_user_data_row)){
echo '<div class="saved_thing">'.__('You have already filled form for appointment for this date').'</div>';
}
else{
$push_form_data=array();
if($_POST['username']){
$user_data=array('username'=>$_POST['username'],'usernamelabel'=>$_POST['usernamelabel']);
$user_name=array('name_data'=>$user_data);
array_push($push_form_data,$user_name);
}
$form_data_all=json_encode($push_form_data);
$done = add_appointment($_POST,$form_data_all);
if($done==true)
{
echo '<div class="saved_thing">'.__('Mange tak. Du hører fra os snarest !').'</div>';
$user_status_mail = "select * from ".$wpdb->prefix."volunteer_app_setting where meta_key='admin_email' OR meta_key='email_send_status' OR meta_key='email_template_accept'";
$get_appointment_send_mail = $wpdb->get_results($user_status_mail);
$event_metadata=unserialize($event_datas_count[0]->pstdata_value);
if($event_metadata['notification_mail']=='1')
{
require_once(dirname(dirname(dirname(dirname(__FILE__))))."/volunteer-appointment/mail/send_mail.php");
$selected_template=$event_meta_data['mail_temp_form_submission'];
$from=$get_appointment_send_mail[0]->meta_value;
$data=array('first_name'=>$_POST['username'],'send_to_admin'=>1,'event_date'=>get_post_meta($_POST['event_id'],'event-date',true),'event_name'=>get_the_title());
$current_user = wp_get_current_user();
$send_mail=mail_user($current_user->user_email,$selected_template,$from,$data);
if($send_mail){
echo '<div class="saved_thing">'.__('E-mail notifikation afsendt til administrator').'</div>';
}
else{
//echo "<script>alert('Mail not send');</script>";
}
}
}
else
{
echo '<div class="saved_thing">'.__('Fejl!!!').'</div>';
}
//}
return;
}
}
}
first we check the data, if its not exist than go to else part.
its is going in if part all the time even data is not exists but saving data . In else part add_appointment() is the issue. this function is saving the data.
I debug
code is checking the condition and if data is not exist in database than go to else part, save data using the function add_appointment() and after executaion of the function again its going to else condition and showing message You have already filled form for appointment for this date
Change your if condition to
from -> if(isset($get_user_data_row))
to -> if(!empty($get_user_data_row))
If no rows are found, it will return 0
if($get_user_data_row > 0) {
// Some code here
} else {
// Some functions here
}

How can I place text that relates to a foreach function, outside the loop?

I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}

Echo content inside foreach only once

I'm trying to echo content inside a foreach once. At the moment, when a form is filled by the user, the message is displayed for every record skipped. If there are 35 records skipped, I will get 35 messages, because of the foreach. I want to avoid this, and be able to display only one echo for the entire results page. How can I do this? I suppose I may have to do this outside the foreach, but I have no clue how to take it out of the foreach.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
if($course->aircraft == '2')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
Assuming you must maintain the structure of that object, you could just have a boolean update if $course->aircraft == 1 then echo accordingly:
$found = false;
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$found = true;
}
}
}
}
if($found)
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
}
You can set a simple flag variable in this case.
$warningEmitted = false;
Then, in your loop prior to emitting a warning:
if(!$warningEmitted) {
// echo warning here.
$warningEmitted = true;
}
The best option would probably be to set your message as a variable, then echo the variable after the foreach is finished.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$message = '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
if(isset($message))
{
echo $message;
}
Outside the loop assume $count=1;
Inside the loop, you can put an if statement.
if($count==1) { $count++; echo "Whatever";}
Hope this helps.
Just use a boolean variable which you set to false initially, and the set it to true in the loop if you get a match.
Then you can check the boolean after the loop has finished to decide if you need to display the message or not.
Create additional variable in which you will store information whether the message was already displayed or not. When you display it, set the var to true.
Assuming I understand you correctly, I think you want to use 'break' to stop looping as soon as a problem is found.
if (Auth::LoggedIn() && Auth::$userinfo->rank == 'Student') {
foreach ($allcourses as $course) {
if ($course->aircraft == '1') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
if ($course->aircraft == '2') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
}
}
Above I've also moved the "if logged in" conditional to be outside the loop (so it's only checked once).
Something to consider:
A more user friendly approach might to add each error into an array - instead of using echo & breaking out - and then loop through that error array at the end, showing with more information about the error so they can be corrected all at once by the end user (depending on how your form works, of course).

Codeigniter Count / If

this is taking me too long to figure out. I am using Codeigniter to query a database.
The model does this
function currentfunction($id)
{
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
}
The controller
$this->load->model('Display');
$results = $this->Display->currentfunction($id);
$this->load->view('current_items', array('currentitems' => $results));
The view
foreach($currentitems as $row){
echo $row['name']
///....do more
}
works just fine EXCEPT IF no rows are returned
then
Message: Invalid argument supplied for foreach()...
How do I handle the if...else...scenario
I tried this Q-A, but doesn't work for me. PlsHlp.
Just do:
if(is_array($currentitems)) {
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else
{
echo "No items in database!";
}
You are getting an error because foreach expects its first argument to be an array. If there are no items in the database however your functions returns false.
This is because when you run your code:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
when there are no rows returned the above code works fine it just doesnt work in the view where you try to run a for loop.
This for loop should not be run if there are no rows returned. yet you are trying to run a forloop even though there are no rows to work with.
My suggestion is changing the code like so:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
$noResults = true;
}
in the view you will have something like this before your for loop:
if($noResults != true){
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else{
//do something
echo "No items in database!";
}
Hope this helps.
PK
Why don't you just do this:
function currentfunction($id)
{
return $this->db->get_where('mytable', array("id =" => $id));
}
In the view, if there are no results, an empty array will be returned and foreach won't throw an error:
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
Much cleaner IMO.
If you want to show an error message in your view, you can do:
if($currentitems->num_rows() > 0)
{
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
}
else
{
// Error message
}
This is better than checking if there are results with if/else twice, like halfdan and Pavan are suggesting.

How to check if results on while($row = mysql_fetch_array in PHP

Im trying to figure out how to handle this is no results are returned, how would I code that?
while($row = mysql_fetch_array($Result))
So like if there a results: print them out
else: show a link
http://ca3.php.net/manual/en/function.mysql-num-rows.php
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) { ... }
} else {
// show link
}
You can use mysql_num_rows() to tell you how many results are found. Using that with a simple if-statement, and you can determine what action to take.
if (mysql_num_rows($result) > 0) {
// do while loop
} else {
// show link
}
Others suggest using mysql_num_rows() but you should be aware that that function works only if you use a buffered query. If you query using mysql_unbuffered_query(), the number of rows in the result is not available.
I would use a simple flag variable:
$found_row = false;
while ($row = mysql_fetch_array($result)) {
$found_row = true;
. . .
}
if ($found_row == false) {
// show link
}
It may seem redundant to set $found_row to true repeatedly, but assigning a literal value to a variable ought to be an insignificant expense in any language. Certainly it is small compared to fetching and processing an SQL query result.
Use even shorter syntax without insignificant mysql_num_rows to save processor time:
if($result) {
// return db results
} else {
// no result
}
I might have figured it out:
if (!($row = mysql_fetch_array($descResult)))
{
echo "<tr><td>Add Link</td></tr>";
}
This can be done without mysql_num_rows() or an additional (flag) variable
if ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo 'no rows in result set';
}
else {
do {
echo $row['X'];
} while ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) );
}
but it duplicates the actual fetch command (one in the if-statement and one in the while-clause).

Categories