I'm trying to enter 100 email addresses separated by ';' and store them in MySql table. What I've tried so far is:
$recipient_raw = $this->input->post('recipient'); //get the 100 emails in $recipient_raw
$recipient_array=explode(';', $recipient_raw); //explode them into an array
$title = $this->input->post('title');
$body = $this->input->post('body');
foreach($recipient_array->result() as $row):
$recipient=array(
'email'=>$row->email //looping through each email; seems I should not use $row->email since there's no title for them
);
$this->db->insert('eamil_send',$this->db->escape($recipient));
endforeach;
I'm running this on CodeIgniter PHP. Error msg is on line foreach($recipient_array->result() as $row):, where it says: Call to a member function result() on a non-object
Any advice is appreciated! Thanks!
result(), is an active record function for converting a database result object. You are creating a standard array.
$batch = array();
foreach($recipient as $row){
$batch[] = array(
'email' => $row
);
}
$this->db->insert_batch('email_send', $batch);
That should do what you're trying to accomplish.
The error message is pretty much self explanatory..
In the 2nd line of your code you declared $recipient_array as an Array(), not an object. So, there's no "result" method available.
Your loop should be
foreach($recipient_array as $row)
On a side note, you probably shouldn't be executing db operations inside a loop (especially, for 100 operations!). Instead, you should save all the queries in one big query string and execute at the end.
If you want your 100 email address be separate by ',' you should use implode(glue, pieces) instead of explode() function. Like on email address that you want to insert.
$recipient_raw = array();
$recipient_raw[] = $this->input->post('recipient');
foreach ($recipient_raw as $value) {
$tem_arr = implode(',', $value);
}
$this->db->insert('eamil_send',$this->db->escape($tem_arr));
Related
I have this raw query that extracts data from the database table in Laravel
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->get();
I get these values: [{"userName":"kim"}]
but I want to extract just the username "kim" itself, not an array. I have tried to do this without success:
$convert1=json_decode($username);
$newusername=$convert1->userName;
but i get an error: Trying to get property 'userName' of non-object
Any idea how I can solve this
Instead of what you're doing, you can just do this:
HotspotUser::where('assignedTo', 786)->pluck('userName');
Now you will have a collection of names; or if you only want the first one:
HotspotUser::where('assignedTo', 786)->first()->user_name;
(I'm not certain if the property will be user_name or userName; you should have simple column names to make things easier.)
You are getting the result of DB as php stdClass object, so you can iterate over it and get every variable that is queried. Something like below code may help you.
In case of using get()
$data = DB::table('hotspot_users')
->where('assignedTo', '786')->select('userName')->get();
foreach ($data as $datum) {
$result[] = $datum->userName;
}
In case of using first()
$data = DB::table('hotspot_users')
->where('assignedTo', '786')->select('userName')->first()->userName;
Hi As you mentioned that is an array [{"userName":"kim"}]
So you have two choices
First , you first insted of get
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->first();
$newusername=$convert1->userName;
Second , get the first element of array
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->get();
$username = reset($username);
$convert1=json_decode($username);
$newusername=$convert1['userName'];
I store the array into session for easily to retrieve and work.
$responses = session('get_all_response');
$responses contains 30 records maximum.
I aiming to make the pushing of data into the array more fast. Because if I have 10 records in $responses (array) it takes 30secs to load all the possible info regarding each content of that array (But the real thing is. The count of records in an array is more likely 30 maximum)
I loop inside the array
foreach($responses as $res)
{
$bo_images = DB::select('SELECT
image.bo_hotel_code,
image.bo_image_type_code,
image.bo_path,
imagetypes.bo_content_imagetype_description
FROM
bo_images AS image
RIGHT JOIN bo_content_imagetypes AS imagetypes
ON imagetypes.bo_content_imagetype_code = image.bo_image_type_code
WHERE image.bo_hotel_code = "'.$res['code'].'" AND image.bo_image_type_code = "COM" LIMIT 1');
if($bo_images != null)
{
foreach($bo_images as $row)
{
$responses[$res['code']]['information']['bo_images'] = array(
'image_type_code' => $row->bo_image_type_code,
'image_path' => 'http://photos.hotelbeds.com/giata/'.$row->bo_path,
'image_type_description' => $row->bo_content_imagetype_description,
);
}
}
$bo_categories = DB::select('SELECT
a.category_code,
b.bo_content_category_description
FROM
bo_hotel_contents AS a
RIGHT JOIN bo_content_categories AS b
ON b.bo_content_category_code = a.category_code
WHERE a.hotel_code= "'.$res['code'].'"');
if($bo_categories != null)
{
foreach($bo_categories as $row)
{
$responses[$res['code']]['information']['rating'] = array(
'description' => $row->bo_content_category_description,
);
}
}
}
In every loop, there is a code in there that will hold the key to get the contents inside the database.
then after that, it will push the content into that array that equal to the index of the array.
Otherwise. It is a success. But I know this is not the proper way of doing it. I know there is much better to do this.
Any help is so much appreciated
I'm not familiar with Laravel, so I don't know if prepared statements work with it, but you should do something to clean &/or verify the $res['code'] to make sure it is an integer, assuming that's what it's supposed to be.
First, prepare a string for an WHERE IN clause.
$str = "";
foreach ($responses as $res){
$str .= ','.$res['code'];
}
$str = substr($str,1); // to remove the comma
Then you'll need to change your query to use the IN statement.
WHERE a.hotel_code IN({$str})
I'm guessing image.bo_hotel_code refers to $res['code']. But in case it doesn't, you could modify your SELECT statement (if memory serves):
$code = $res['code'];
SELECT {$code} as code,
image.bo_hotel_code,
image.bo_image_type_code,
...
Then you'll loop over the results and put them into the array in the same manner, where $row['code'] would refer to the code used to select it. It should be MUCH faster than running repeated queries, and there should be one row for each code in the IN statement.
This is in reference to the post made here: insert multiple rows via a php array into mysql
My question is, can anyone explain this in more detail? I dont understand what $data and what $row is or does.
I'm pulling in many variables from a form like: $Customer = $_POST['Customer']; So if someone can show an example of how to use this code with multiple variables, it would be real nice.
$sql = array();
foreach( $data as $row )
{
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
from: PHP: foreach - manual
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
In this code, $data is an array. On each iteration, foreach will assign the value of the current row to $row. This is equivalent to:
for($i=0;$i<sizeof($data);$i++)
{
$row = $data[$i];
//use $row however u want
}
For example:
$data[0]['text'] = 'text for category1';
$data[0]['category_id'] = '1';
$data[1]['text'] = 'text for category2';
$data[1]['category_id'] = '2';
$data[2]['text'] = 'text for category3';
$data[2]['category_id'] = '3';
After running your foreach using this $data variable, if you use var_dump($row), you will get something like this:
array(3) {
[0] =>
string(25) "("text for category1", 1)"
[1] =>
string(25) "("text for category2", 2)"
[2] =>
string(25) "("text for category3", 3)"
}
The last line will implode this array to create a valid mysql query.
PS: By the way, mysql extension is deprecated. You should learn mysqli - mysql improved or mysql pdo - php data objects
I am sending an array of numbers separated by commans to server. Basically on server database I have a field that cotains numbers.Server side code checks which numbers are in database and send me the array of those numbers.
Following code is what I am using...
public function already_user()
{
$contacts=$this->input->post('contact');
//$contacts is an array.
$user= explode(',',$contacts);
foreach($user as $number)
{
$data = array (
'username' =>$number
);
$usernumber = $this->chat_model->get(array('username'=>$number)); // a simple query to datbase that check if number exists in database column or not.
if(!$usernumber==""){
$value[]=$usernumber;
}
}
echo json_encode($value);
}
Only drawback about this code is , its extremely slow.... If i have 1000+ numbers it takes a minute.since its a loop Is there any way to fasten this up. Any single mysql query??
Why don't you just write a single query? Parse the string to get an array and query the table in a single go.
$contact_array = array_map('trim', explode(', ', $contacts));
$all_usernumbers = $this->chat_model->get(array('username IN'=> $contact_array));
which should (depending of what your chat_model->get() accepts), translate to:
SELECT * FROM your_table WHERE username IN ('123', '345')
This is all pseudocode since I don't know what your framework accepts but the SQL query above should be valid.
Assuming that the mysqli object is already instantiatied (and connected) with the global variable $mysql, here is the code I am trying to work with.
class Listing {
private $mysql;
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
return $info;
}
}
there are several hundred listings in the db and when I call $result->fetch_array() it places in an array the first row in the db.
however when I try to call the object, I can't seem to access more than the first row.
for instance:
$listing_row = new Listing;
while ($listing = $listing_row->getListingInfo()) {
echo $listing[0];
}
this outputs an infinite loop of the same row in the db. Why does it not advance to the next row?
if I move the code:
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
if I move this outside the class, it works exactly as expected outputting a row at a time while looping through the while statement.
Is there a way to write this so that I can keep the fetch_array() call in the class and still loop through the records?
Your object is fundamentally flawed - it's re-running the query every time you call the getListingInfo() method. As well, mysql_fetch_array() does not fetch the entire result set, it only fetches the next row, so your method boils down to:
run query
fetch first row
process first row
return first row
Each call to the object creates a new query, a new result set, and therefore will never be able to fetch the 2nd, 3rd, etc... rows.
Unless your data set is "huge" (ie: bigger than you want to/can set the PHP memory_limit), there's no reason to NOT fetch the entire set and process it all in one go, as shown in Jacob's answer above.
as a side note, the use of stripslashes makes me wonder if your PHP installation has magic_quotes_gpc enabled. This functionality has been long deprecrated and will be removed from PHP whenever v6.0 comes out. If your code runs as is on such an installation, it may trash legitimate escaping in the data. As well, it's generally a poor idea to store encoded/escaped data in the database. The DB should contain a "virgin" copy of the data, and you then process it (escape, quote, etc...) as needed at the point you need the processed version.