check if record exist in Laravel 5.5 [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dynamic input form, I want to check if the record exists, if no then it can not insert data
my controller
$user = Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->get();
if($user->isEmpty()){
// insert
}else{
//message "cannot input"
}
if insert one data, success.. but if insert array in my controller not check..
why in input array data always insert???

This is pseudo for only check id_b
$data = [1,2,3,4];
$data_a = [1,2,3,4];
$masters = Master::whereIn('id_b', $data)->whereIn('id_a', $data_a)->get();
foreach($data as $key => $value) {
$isExisted = false;
foreach ($masters as $master) {
if ($master->id_b == $value[$key] && $master->id_a == $data_a[$key])
{
$isExisted = true;
break;
}
}
if ( ! $isExisted) {
$master = new Banner();
$master->value = your_data;
$master->save();
}
}

You could use exists()
if(Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->exists()) {
do something
}
Also I would suggest you reduce the amount of in-line stuff you're doing, instead something like this:
$id_a = $request->get('id_a');
$id_b = $request->get('id_b');
if(Master::where('id_a','=', $id_a)->where('id_b','=',$id_b)->exists()) {
do something
}

If I understand correctly, you want to insert a Master if a given id_a and id_b doesn't already exists for one Master
If so, you could actually use firstOrCreate :
Master::firstOrCreate(
['id_a' => $request->get('id_a'), 'id_b' => $request->get('id_b')],
['yourcolumntocreate' => columnvalue, ...]
)

Related

What is the best way to store large amounts of data in an array? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a database of 100,000 contacts.
I have a multiple select box which I would like to use to select contacts to add to a specific mailing list.
My problem is that I am currently storing the data for the mailing list in a serialized array format (PHP) in MySQL.
When I select over a certain number of contacts, something seems to break (I assume not enough memory) and does not update the array.
Is there a best way to store a large array in MySQL and is there a best way to keep memory usage in a PHP array() low?
Code Example
if(isset($_POST['add'])) {
$name = $core->EscapeString($_POST['name']);
$desc = $core->EscapeString($_POST['desc']);
foreach($_POST['addSelect'] as $null => $id) {
if(!in_array($id, $recipientArray)) {
$recipientArray[] = $id;
}
}
$contacts->updateML($lid, $name, $desc, serialize($recipientArray));
}
else if(isset($_POST['rm'])) {
$name = $core->EscapeString($_POST['name']);
$desc = $core->EscapeString($_POST['desc']);
foreach($recipientArray as $null => $id) {
foreach($_POST['rmSelect'] as $null1 => $id1) {
if($id == $id1) {
unset($recipientArray[$null]);
}
}
}
$contacts->updateML($lid, $name, $desc, serialize($recipientArray));
}
UpdateML Function
//Class 3, Function 16
function updateML($lid = '', $name = '', $desc = '', $recip = '') {
global $MySQLi;
$query = "UPDATE `mailing_lists` SET `name` = '".$name."', `desc` = '".$desc."', `recipients` = '".$recip."' WHERE `list_id` = '".$lid."' LIMIT 1";
$commit = $MySQLi->query($query);
if($commit == false) {
die("Issues with the database were detected. Please email peter#domain.com quoting error code: <strong>CLASS3/16.1</strong>.");
}
else
{
return true;
}
}
You need 2 tables. One for Mailing List Definition, one for recipients. In recipients table you'd need to have a foreign key relating the record to appropriate mailing list.
so mailing_lists table looks like this:
ml_id
name
desc
and recipients looks like this:
r_id
email
ml_id
First add the mailing list to the database:
INSERT INTO mailing_lists SET name = 'my first list', desc = 'mailsareus'
When you add new recipients just add a new row to recipients table:
INSERT INTO recipients SET email = 'xxx#mail.com', ml_id = 1
If you need to get all the recipients and definition from a mailing list just use a join
SELECT * FROM mailing_lists JOIN recipients ON recipients.ml_id = mailing_lists.ml_id

exploded string manipulation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have already seen examples for string manipulation using "explode" but none of them does my job..
I have an array of exploded strings:
$grand_result = 12,5,7,3,2,1 ;
$grandparent_id = explode(",",$grand_result);
i want to insert some values in db having id = $grand_result except first value returned (12) in this case
$grand_result can have many values i want to fetch only first 7 values..
how can i do that ...thanks in advance
you can use array_slice
$output = array_slice($grandparent_id, 0, 7);
$grand_result = "12,5,7,3,2,1" ;
$grandparent_id = explode(",",$grand_result);
first update
$avoid = grandparent_id[0];
foreach ($grandparent_id as $id) {
if ($avoid != $id) {
//run your update query
}
}
second fetch
$query = "select * from `table_name` where id in (".$grand_result.") limit 7";
Set Limit of explode
$grand_result = 12,5,7,3,2,1 ;
$grandparent_id = explode(",",$grand_result,8);
unset($grandparent_id[7]); or $grandparent_id = array_slice($grandparent_id, 0, 7);

Next statement in a While Loop with PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Ok i have a while loop function in my site that pulls in excel documents and parses them to the database i want to check for duplicates and if duplicate skip it:
$content = file($selectfile1);
$posted_content = array();
list($rownum, $row) = each($content);
$posted_content[0] = explode(",", $row);
array_push($posted_content[0], "ID");
$count = 0;
// iterate each row (1 post)
while (list($rownum, $row) = each($content))
{
$count++;
$cols = "orderid, created_at, updated_at, notification_type, radius, available, expiration, ";
$vals = "";
$cols2 = "equipment_id";
$vals2 = "";
....{parsing data)...
}
i want to write in a script that checks to see if the record is a duplicate and if not enter it.
$sql25 = "SELECT * FROM notifications WHERE origin =" . $origin_id . " user_id =12039";
$rs25 = $conn->Execute($sql25);
if($rs25->RecordCount() == 1 || $rs25->RecordCount() >= 1)
{
here is where i need a command. Can you use? next()
--------------------------------------------------
}
else
{
Insert query
}
You are looking for the continue statement.
From the docs:
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
(See http://www.php.net/manual/en/control-structures.continue.php)
example:
<?php
while ( ... ) {
if ($foo = 'bar') {
// skip to the next iteration
continue;
}
}

equivalent to foreach loop for just one row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a PHP function that runs a SELECT Query in SQL:
if(!function_exists("SelectQuery")) {
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
return $NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
return $SelectQuery_Results;
}
}
then i am calling it here:
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
foreach($ticket as $ticket2) {
}
rather than using a foreach loop what else could i use as my query will only be returning one row and i dont want to put my whole page within a loop
i tried just removing the foreach loop but that didnt work
Just access your value as $ticket[0].
A function cannot return two values for a single call. So, remove
return $NumRows=mysql_num_rows($SelectQuery);
You can check the array size for the number of rows in result.
If you want to echo out the result the following code will be ok!
if( sizeof($ticket) > 1 ){
foreach($ticket as $ticket2){
for($i=0; $i<sizeof($ticket2)/2; $i++)
echo "[" . $ticket2[$i] . "]";
echo "<br />";
}
}
$ticket is an integer see :
return $NumRows=mysql_num_rows($SelectQuery);
So you juste have to use $ticket.
If you want the row, remove this useless return in the SelectQuery function and use $ticket[0] for the first and only row.
Change the function with this :
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
$NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
if ($numRows>1) {
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
}
else $SelectQuery_Results = mysql_fetch_array($SelectQuery);
return $SelectQuery_Results;
}
Then use :
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
if (is_array($ticket)) { foreach loop; }
else { use directly ticket['attribute'] }

why auto dupplicate value in my array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I tried to create a shopping basket in my project, but some problem to handle this.
My project basket must allow duplicate value, but my code auto duplicate last insert to array. Why does this happen, and how to solve this auto duplicate?
<?php
if(isset($_SESSION['basket'])){
$point = count($_SESSION['basket']);
echo " point = ".$point;
$value = end((array_keys($_SESSION['basket'])));
$value++;
}else{
$value = 0;
echo " point = 0";
}
if(isset($_GET['id'] , $_GET['meter'] , $_GET['color'])){
$id = $_GET['id'];
$color = $_GET['color'];
$meter = $_GET['meter'];
$selected_product = array($id , $color , $meter);
list($_SESSION['basket'][$value][0],$_SESSION['basket'][$value][1] , $_SESSION['basket'][$value][2]) = $selected_product;
echo "<pre>";
var_dump($_SESSION['basket']);
echo "</pre>";
}
?>
Though its not exactly clear from your question. To remove duplication in array use array_unique()
You also had a typo at
array($_SESSION['basket'][$value][0],$_SESSION['basket'][$value][1] , $_SESSION['basket'][$value][2]) = $selected_product;

Categories