Select Query from two tables in codeigniter - mysql

I have 2 tables:
Events and Registration.
Events Fields: EventID and EventName
Registration Field: MemberID and Name
I want to pull the EventName and the Name- of the person. How do I do this with a model?
The code I have:
Model
function getAll()
{
$query = $this->db->get('tblRegistration');
if( $query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
return $data;
}
controller
public function getallevents() {
$this->load->model('events_model');
$data['records'] = $this->events_model->getAll();
$this->load->view('view-events', $data);
}
View
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->Name</td>";
// echo "<td> $row->intLocationID</td>";
echo "</tr>";
endforeach;
Edit
OK I have added the data that I want out of the table.
model
function getAll()
{
// get all the records from the schools table
$this->db->select('*');
$this->db->from('tblRegistration as reg');
$this->db->join('tblMeetRace as met', 'reg.intMeetRaceID = met.intEventID');
$query = $this->db->get();
// if the number of rows returned is more than 0
if( $query->num_rows() > 0) {
// loop through each record (row) and place that
// record into an array called $data
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
// return the array to the controller
return $data;
}
view
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->intMeetRaceID/td>";
echo "<td> $row->intEventID</td>";
echo "</tr>";
endforeach;
but I get an error of:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view-events.php
Line Number: 89

First of all you need to add another column in your events table for storing the MemberId, say memberid.
Once you have that, when ever a member registers for an event, you can store his ID in the events table and relate it.
Then you can use Joins to fetch the datas
$this->db->select('*');
$this->db->from('registration as reg');
$this->db->join('events as evt', 'reg.id = evt.memberid');
$query = $this->db->get();

Related

How to retrieve composite column from Cassandra table in PHP

I have a CassandraHandler that retrieves the queries in rows
class CassandraHandler
{
private $keyspace = 'blabla'; //default is oyvent
private $cluster = NULL;
private $session = NULL;
function __construct(){
$this->cluster = \Cassandra::cluster()
->build(); // connects to localhost by default
$this->session = $this->cluster->connect($this->keyspace);
}
/**
* #return Rows
*/
public function execute($query){
$statement = new \Cassandra\SimpleStatement($query);
$result = $this->session->execute($statement);
return $result;
}
}
When I use for normal columns it's fine but I can't get my photo column in php
I created the column like this
photos frozen<set<map<text,text>>>
my json example
{{"urllarge": "1.jpg", "urlmedium": "2.jpg"},
{"urllarge": "3.jpg", "urlmedium": "4.jpg"}}
And here how can I use PHP to retrieve the composite columns?
$cassandraHandler = new CassandraHandlerClass();
$rows = $cassandraHandler->fetchLatestPosts($placeids, $limit);
foreach ($rows as $row) {
$tmp = array();
$tmp["userid"] = doubleval($row["userid"]);
$tmp["fullname"] = $row["fullname"];
$tmp["photos"] = $row["photos"] //????????
}
I know there is this documentation of the PHP driver https://github.com/datastax/php-driver
But I am a little confused.. I just need to get the json value like I get in cqlsh
You have two options to convert the composites into useable JSON:
Create a function to convert the deserialized/unmarshalled objects into JSON.
Retrieve the values from Cassandra as JSON.
Here is an example that demonstrates both options:
<?php
$KEYSPACE_NAME = "stackoverflow";
$TABLE_NAME = "retrieve_composites";
function print_rows_as_json($rows) {
foreach ($rows as $row) {
$set_count = 0;
echo "{\"photos\": [";
foreach ($photos = $row["photos"] as $photo) {
$map_count = 0;
echo "{";
foreach ($photo as $key => $value) {
echo "\"{$key}\": \"{$value}\"";
if (++$map_count < count($photo)) {
echo ", ";
}
}
echo "}";
if (++$set_count < count($photos)) {
echo ", ";
}
}
echo "]}" . PHP_EOL;
}
}
// Override default localhost contact point
$contact_points = "127.0.0.1";
if (php_sapi_name() == "cli") {
if (count($_SERVER['argv']) > 1) {
$contact_points = $_SERVER['argv'][1];
}
}
// Connect to the cluster
$cluster = Cassandra::cluster()
->withContactPoints($contact_points)
->build();
$session = $cluster->connect();
// Create the keypspace (drop if exists) and table
$session->execute("DROP KEYSPACE IF EXISTS {$KEYSPACE_NAME}");
$session->execute("CREATE KEYSPACE {$KEYSPACE_NAME} WITH replication = "
. "{ 'class': 'SimpleStrategy', 'replication_factor': 1 }"
);
$session->execute("CREATE TABLE ${KEYSPACE_NAME}.{$TABLE_NAME} ( "
. "id int PRIMARY KEY, "
. "photos frozen<set<map<text, text>>> )"
);
// Create a multiple rows to retrieve
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "1, "
. "{{'urllage': '1.jpg', 'urlmedium': '2.jpg'}, "
. "{'urllage': '3.jpg', 'urlmedium': '4.jpg'}}"
. ")");
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "2, "
. "{{'urllage': '21.jpg', 'urlmedium': '22.jpg'}, "
. "{'urllage': '23.jpg', 'urlmedium': '24.jpg'}}"
. ")");
// Select and print the unmarshalled data as JSON
$rows = $session->execute("SELECT photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
print_rows_as_json($rows);
// Select the data as JSON and print the string
$rows = $session->execute("SELECT JSON photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
foreach ($rows as $row) {
echo $row["[json]"] . PHP_EOL;
}
From the above example you can see that selecting the data as JSON involves less code for your application while also moving the processing onto the server. This probably the preferred choice for your application needs.
NOTE: This example is using v1.3.0 of the DataStax PHP driver which added support to pass a query strings directly to Session::execute() and Session::executeAsync(). If you are using an earlier version you will need to convert all query strings to Cassandra\Statement objects before passing to $session->execute(...).

Find how many times every word is repeated in db

Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);

moving specific field value to another table before deleting the whole row

I have a table with 7 fields, when I delete a row from the table by id i want two fields of that row to be inserted into another table with just two columns.
This is my controller function
public function refund() {
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}
these are model functions
public function delete_accounts_data($id) {
$this->db->where('id', $id);
$this->db->delete('accounts');
}
public function insert_refund($data){
$this->db->insert('refund', $data);
}
Suppose this the row i will delete
id|name|barcode|refunded_amount|commission
01|asd |2342342| 53.01 | 5.32
on the other hand i will insert as
id|barcode|refunded_amount
01|2342342| 53.01
You should try and debug your code for general errors, e.g,
1) Try to set the environment to development in index.php.
2) Add some debugging code in your function to check for errors.
function refund(){
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
echo $this->db->last_query(); //will produce the query for fetching the details by id
if( isset( $accounts ) && count( $accounts ) > 0 ){
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
print_r( $data );
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}else{
echo "NO DATA FOUND";
}
}

where am i going wrong in my extraction of value from mysql database?

where am i going wrong in my extraction of country name from mysql database? (codeigniter: activerecord enabled)
Its printing out "default country" instead of expected "Australia".
Pages Controller
public function view($page)
{
$page = strtoupper($page); // Capitalize the first letter
$data = array(
'title' => 'My Title',
'country' => 'default country'
);
$this->getCountryName($page, $data);
if(!is_null($data['country'])){
$page = "country";
}
$this->load->helper('url');
$this->load->helper('utility');
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
if(!is_null($data['country'])){
$this->load->view('templates/infobox', $data);
}
$this->load->view('templates/footer', $data);
}
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data['country'] = $row;
echo $row;
}
}
}
Country View
<div style =" position:absolute;top:90%; background: red;">
<?php echo $country; ?></div> // prints default country.
</div>
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: pages/country.php
Line Number: 25
so i put in some more debugging and found the correct syntax/method to call to get the result,
which then returns an object with attributes that need to be accessed in the view.
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['country'] = $query->row();
}
}
<?php echo $country->name; ?>

simple codeigniter query + results display won't display

I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.
I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.
Any idea how I can get this to work? Code below.
Controller
function displayMovies() {
$this->load->model('movie_list_model');
$data['movielist'] = $this->movie_list_model->getList();
$this->load->view('movielist_view', $data);
}
Model
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row)
{
echo $row['firstname'];
echo $row['lastname'];
echo $row['favorite_movie'];
}
}
View
<?php foreach($movielist as $mlist)
{
echo $mlist->firstname . '<br />';
echo $mlist->lastname . '<br />';
echo $mlist->favorite_movie;
}
?>
If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.
A safety would be including something like this in your view:
if($movielist)
{
/* foreach() {} */
}
Also, your model should only return data (not echo it).
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result(); /* returns an object */
// Alternatively:
// return $query->result_array(); /* returns an array */
}
I also recommend using Active record:
function getList() {
$this->db->select('firstname');
$this->db->select('lastname');
$this->db->select('favorite_movie');
$query = $this->get('movies');
return $query->result();
}
Good luck!