Where Operator In Laravel - php

I need to use where operator to check some ids in my table as the following
$subScIDs = SubjectSchedule::where('subject_start_id',Input::get('substID'))
->whereNull('deleted_at')
->select('id')->get();
$subScIDsArray = array() ;
foreach ($subScIDs as $id)
{
$subScIDsArray [] = $id->id ;
}
// here my issue
$subScInStudAttends = StudentAttendees::whereIn('subject_schedule_id',$subScIDsArray)
->select('subject_schedule_id')->get();
if ($subScInStudAttends)
{
return " true " . $subScInStudAttends;
}else{
return "false";
}
My issue in this code
$subScInStudAttends = StudentAttendees::whereIn('subject_schedule_id',$subScIDsArray)
->select('subject_schedule_id')->get();
whereIn working well it fetch any id in $subScIDsArray, but i need to check each id of ids if one id in $subScIDsArray not equal subject_schedule_id' return false ;
How I Can do it ?
Any Suggestions ?

You can check the length of the array that contains the ids against the length of the records returned.
if( count($subScIDsArray) == count($subScInStudAttends) ){
// all IDs in the array have a corresponding record in the database
}
Or better, if your application logic permits it, simply get the count of the records and then compare with the length of the ids array.
$subScInStudAttendsCount = StudentAttendees::whereIn('subject_schedule_id', $subScIDsArray)->count('subject_schedule_id');
if( count($subScIDsArray) == $subScInStudAttendsCount ){
// all IDs in the array have a corresponding record in the database
}
This code assumes the ids in your database are all unique.

Related

How to merge multiple column into one, make it looped but divided by row with duplicate id with PHP and OracleSQL?

I've code but I cant make it like I want, the requirement is make the data I've to repeat the data owned by same id through just one column, although from real database it separated (different column), so this is the data I've
number pay_status card_status
021998877 UNPAID ACTIVE
021998875 NULL NOT ACTIVE
021998875 NULL ACTIVE
And I want to change it like this:
number others
021998877 ACTIVE
021998877 UNPAID
021998876 NOT ACTIVE
021998875 ACTIVE
Now I just can to get output like this:
021998877 ACTIVE UNPAID
and this is my code for the output
while ($row = oci_fetch_assoc($stid)) {
printf("<tr><td>%d</td><td>%s</td></tr>\n", $row['no'],
$row['card_status'],$row['pay_status'] );
I'm using PHP and OracleSQL for the database. Please help, thank you
So I think you are saying, if the card_status is not NULL then print a second line.
In that case this would do it quite simply.
while ($row = oci_fetch_assoc($stid)) {
printf("<tr><td>%d</td><td>%s</td></tr>\n",
$row['no'],
$row['pay_status'] );
if ( $row['card_status'] != 'NULL' ) {
printf("<tr><td>%d</td><td>%s</td></tr>\n",
$row['no'],
$row['card_status'] );
}
}
You may need to amend the test for NULL depending on what that value actually is on the result set!
From your comment it counds like you have more than the 3 columns in the row than you mentioned initially.
To do this for multiple columns in the resultset you can loop over the columns in the resultset and print the result over many rows in your output, converting NULL to the string 'NULL'.
while ($row = oci_fetch_assoc($stid)) {
foreach ( $row as $colname => $value) {
if ( $colname == 'no' ) {
continue; // ignore the key field column
}
$value = $value == NULL ? 'NULL : $value
printf("<tr><td>%d</td><td>%s</td></tr>\n",
$row['no'],
$value );
}
}
}

Get random element from MySql using Laravel 5.4

I display an element randomly from my test table, so how can I get the id of this element:
$tests= DB::table('test')->inRandomOrder()->limit(1)->get();
because I want to compare it with an other id
->get() returns a Collection or records from your test table. You need to use a loop to compare a single record's value:
$id = 1; // Or whatever you're comparing to
$tests = DB::table('test')->inRandomOrder()->limit(1)->get();
foreach($tests AS $test){
dd($test->id == $id);
}
Or simply use ->first() to return a single record from test:
$id = 1;
$test = DB::table('test')->inRandomOrder()->first();
dd($test->id == $id);
->get(); method return instance of \Illuminate\Database\Eloquent\Collection. For getting a single instance use ->first();method. See also official docs https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset For example.
$test = DB::table('test')->inRandomOrder()->first();
if ($test->id == $id) {
// your logic
}

Prevent duplicate ids from being added to session (array)

I got a session which adds ids to an array, the problem is every id gets added even if the id is already present. How can I prevent duplicate id's from being added to the array?
I figured I need to check for the id using in_array but I don't know exactly how to use it correctly.
I send the id of the product to my quote page using this link:
<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>
Then on that page I use the following code:
if(!isset($_SESSION['product'])){
$_SESSION['product'] = array();
}
// CHECK FIRST THAT $_GET['product'] IS SET BEFORE ADDING IT TO SESSION
if( isset($_GET['product'])){
$_SESSION['product'][] = $_GET['product'];
}
$prods = implode(",", $_SESSION['product']);
And finally load all the products with the ids that are inside the array:
if(count($_SESSION['product']) != 0){
// offerte overzicht
$offerte = "SELECT * FROM `snm_content` WHERE `id` in (".$conn->real_escape_string($prods).") AND state = 1";
$offertecon = $conn->query($offerte);
$offertecr = array();
while ($offertecr[] = $offertecon->fetch_array());
}
But now everytime I reload the page, the id is added again, it's not really bad since the products are only loaded once, but still I would like to fix this, because I think a query checking for tons of duplicate ids is not the best way.
Using in_array is simple - you just check if element is in array:
var_dump(in_array($element, $array));
In your case it is:
var_dump(in_array($_GET['product'], $_SESSION['product']));
And the check is:
// i advise you to check product value as `int`.
// Because values as `empty string` or `0` or `false` are considered set
if( 0 < intval($_GET['product']) && !in_array($_GET['product'], $_SESSION['product']) ) {
$_SESSION['product'][] = $_GET['product'];
}
But the more clever solution is to use product id as an array key with some fixed value (1 or true for example):
$_SESSION['product'] = [
'101' => 1,
'102' => 1,
'106' => 1,
];
In this case you don't even need to check if your key exists - if it exists it will be overwritten, if not - will be added:
if( 0 < intval($_GET['product']) ) {
$_SESSION['product'][ $_GET['product'] ] = 1;
}
// but here you need to take array keys instead of values
$prods = implode(",", array_keys($_SESSION['product']));
Option 1
Use in_array() to prevent duplicates:
// CHECK FIRST THAT $_GET['product'] IS SET BEFORE ADDING IT TO SESSION
if( isset($_GET['product'])){
if(!in_array($_GET['product'], $_SESSION['product']){
// product not exists in array
$_SESSION['product'][] = $_GET['product'];
}
}
Option 2 empty array before adding products
//if(!isset($_SESSION['product'])){
$_SESSION['product'] = array();
//}

How to filter foreach array for integers

I have a for-each statement based off a php generated query..
I am trying to figure out how I can make sure all the IDDestinations of the records are the same.
For example in my current query I have 2 records with an IDDestination of 12, one record with an IDDestination of 9 and the last is 3.
I know how to do this in the query but I am trying to generate a message to the user if the IDDestinations are not equivalent.
My code so far.
foreach($results as $row) {
$IDDestination =(int) $row['IDDestination'];
if ($IDDestination == $IDDestination){
echo "<script>alert('All Courses Match Destination.');</script>";
} else {
echo "<script>alert('Courses have different Destinations);</script>";
}
var_dump($IDDestination);
}
This is currently just verifying that each record has an IDDestination Present and tells ME All courses Match.
How can I make it so the INTEGERS are equivalent and give me the same message?
Here's one way; use a variable outside your loop to determine if it's ok or not:
$everything_matches = true;
$id = null;
foreach($results as $row) {
// Set it for the first record.
if($id === null)
$id = $row['IDDestination'];
// If the current iteration's ID matches the first record, $everything_matches
// will stay true, otherwise it's false and we should kill the loop.
if($id != $row['IDDestination']) {
$everything_matches = false;
break;
}
}
// Output your message
$message = $everything_matches ? 'All courses match destination.' : 'Courses have different destinations.';
echo '<script>alert("' . $message . '");</script>';

How i will make a LIKE search in the following code?

I've got the following code which is something like a form search engine with multiple inputs where the results are kinda absolute concerning the number of characters etc(perfect match)
.
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres=array();
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field) {
// get existing field value from POST, mark missing or empty value as FALSE
${$field} = isset($_POST[$field]) && trim($_POST[$field])!=''
? trim($_POST[$field]) : false;
// add to array of WHERE clauses only if value is not FALSE
if (${$field}) { $wheres[]="$field='".${$field}."'"; }
}
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE ".
(!empty($wheres) ? implode(" AND ",$wheres) : '1=1').
";";
What i want to do is add an input in the form
<label for="special">Special Search</label>
<input type="text" name="special" id="special_search">
where the user would be able to search in the case_reference field and get the results that match the first four characters. Also i would like this new input to work the same as the others as far as the AND or OR and TRUE or FALSE statements are concerned.
All help appreciated thank you in advance:)
UPDATE : Instead of rewriting the whole thing i came up with the following code at the begining of my previous :
$joker = $_POST['special'];
$joker1 = substr($joker1, 0, 4);
if(isset($_POST['case_reference']) && !empty($_POST['case_reference'])
&& empty($_POST['special'])) {
} else { $_POST['case_reference'] = $joker1; }
It is working for now but anyone can confirm that it would be okay in future??
From the SQL:
$sql="SELECT * FROM jobs WHERE ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Just simply add a variable for special:
$special = $_POST['special']; // this will get the data from the textbox
then add it to the sql statement
$sql="SELECT * FROM jobs WHERE LIKE $special 'aaaa%' AND ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Rewritten avoiding variable variable names, and using mysql_real_escape_string (although you should use mysqli or pdo):-
<?php
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres = array('1=1');
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field)
{
// get existing field value from POST, mark missing or empty value as FALSE
if (isset($_POST[$field]) && trim($_POST[$field])!='')
{
$wheres[]="`$field`='".mysql_real_escape_string(trim($_POST[$field]))."'";
}
}
if (isset($_POST['special']) && trim($_POST['special'])!='')
{
$wheres[] = " case_reference' LIKE '".mysql_real_escape_string(trim($_POST['special']))."%'";
)
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE (".implode(" AND ",$wheres).") ;";
?>

Categories