Select one value from table and pass it to variable - php mysql - php

I want to create variable called $start. As a value I want to select one value from column called timestamp from the last row of my table called table_ex. So far I have this:
class Main {
//some other code
function dataBaseConnect(){
//well working part
}
function getTimeValue(){
$sql = "SELECT `timestamp` FROM `table_ex` WHERE id=(SELECT MAX(id) FROM `table_ex`)";
$this->start = $this->handler->query($sql, PDO::FETCH_COLUMN, 0);
}
function printVal(){
$this->dataBaseConnect();
$this->getTimeValue();
$this->messOuput = "Sth text " .$this->start;
}
}
The problem is that variable is not getting that value I wanted. Could anyone explain me where is the problem?

Maybe this will work for You:
function getTimeValue()
{
// note the table name is now used in the inner query
$sql = "SELECT `timestamp` FROM `table_ex` WHERE id=(SELECT MAX(id) FROM `table_ex`)";
$this-start = $this->handler->query($sql, PDO::FETCH_COLUMN, 0);
}

Related

Laravel Eloquent Builder: Get selected columns

I have a object (Illuminate\Database\Eloquent\Builder) that have a (Illuminate\Database\Query\Builder) inside it. I dump the object and can see this:
The image bellow, is a dd($querybuilder) from the object
My plan is to get the query and extract the selected columns but I already tried ($querybuilder->query) and ($querybuilder['query']) and I received errors.
How can I get the "columns" value?
Solved. Thank you
Tim Lewis
$query->getQuery()->columns worked!
Im posting where what im tying to do. select and addSelect are not doing what I wanted if no colunms are selected.
public function scopeAddStatusColumn($query)
{
$previous_columns = $query->getQuery()->columns;
$status_column = DB::raw('(begin <= NOW() AND end >= NOW()) OR (begin <= NOW() AND end IS NULL) as status');
$new_columns = $previous_columns == null ? ['*', $status_column] : [$previous_columns] + [$status_column];
$query = $query->select($new_columns);
return $query;
}
If you want to get all the columns of the table:
$query = Products::where('product_name', 'pencil')->get();
If you want to get a spesific column:
$query = Products::where('product_name', 'pencil')->get(['product_id']); // this is an array, you can get any column name here
If you want to get value of a single column:
$query = Products::where('product_name', 'pencil')->first(['description'])->description;

PHP - Mysql: Create variable for undefined index

I know how to select from a database, my question is i want to set a variable for a where clause in my query, so lets say select * FROM Foo WHERE A = '$a', but the variable has not been set previously and is from the table i am trying to select from.
So how would i do this.
PHP
$FC_ID = mysqli_real_escape_string($dbc,[]);
$FOOD_sel = $dbc->query("SELECT * FROM Food_Cat WHERE Food_Cat_ID = '$FC_ID'");
That is how far i have got so far.
Try to use sub query for that $FC_ID value
sub query method
$FC_ID = mysqli_real_escape_string($dbc,[]);
$FOOD_sel = $dbc->query("SELECT * FROM Food_Cat WHERE Food_Cat_ID = (select FC_ID from your table )");

PHP MySQL Query insert Function

Is there any possibilty to add a function-call in a SQL-Query?
At the moment i'm doing this:
§sql = "SELECT * FROM TABLE";
But I want, that I'm using a field from my table and call with this a function, which return me true or false.
Maybe a example could explain it better:
"$sql = SELECT * FROM TABLE WHERE functionCall(TABLE.FIELD)=true";
Then I just get all entrys from TABLE, where my function returns true.
Is there any possibility to do that?
you could use If condition before like that :
$sql = "SELECT * FROM TABLE";
fetch your query here
If(functionCall($row['FIELD'])==true) {
your wished code here
.......
}

PHP: Using '$this' within a '$this'?

Probably a bit of a newbie question, but I'm self-taught, and I'm trying to edit some code that is out of my comfort zone, and coming unstuck. Please help!
It is a function that selects data from a MySQL database and returns an array. It uses a couple of other 'core' functions to help with the DB connections.
The original script looks like this:
class Core{
protected $db, $result;
private $rows;
public function __construct() {
$this->db = new mysqli('localhost', 'root', 'password', 'db');
}
public function query($sql){
$this->result = $this->db->query($sql);
}
public function rows(){
for($x = 1; $x <= $this->db->affected_rows; $x++){
$this->rows[] = $this->result->fetch_assoc();
}
return $this->rows;
}
}
class Chat extends Core{
public function fetchMessages(){
$this->query("
SELECT `chat`.`message`,
`users`.`username`,
`users`.`user_id`
FROM `chat`
JOIN `users`
ON `chat`.`user_id` = `users`.`user_id`
ORDER BY `chat`.`timestamp`
DESC
");
return $this->rows();
}
}
The problem is, within the fetchMessages() function in the Chat class there is a SELECT clause which JOINS the "chat" table with the "users" table to fetch the username. If, for whatever the reason, (deleted, banned, quit, etc), the user ID doesn't exist in the user table, the SELECT clause returns no results.
In order for it still to return the message if the user doesn't exist, I think I need to seperate the JOIN into 2 SELECT CLAUSES:
First, SELECT message, user_id FROM chat ORDER BY timestamp DESC;
Then, SELECT username FROM users WHERE user_id = $user_id and RETURN "Guest" if no rows are found.
(I have got the pseudo-code or logic right in my head, I just can't code it!)
My problem is, because I am using the $this-> notation, I don't know how to include a second instance inside the function. What I want to do is something like this:
public function fetchMessages(){
$this->query("
SELECT `message`, `user_id` FROM `chat` ORDER BY `chat`.`timestamp` DESC
");
$rows = $this->rows();
foreach ($rows as $row) {
$uid = $row['user_id'];
$this[2]->query("
SELECT `username` FROM `users` WHERE `user_id` = `$uid`;
");
$user = $this[2]->rows();
if ( $user['username'] == "" ) {
$username = "Guest";
} else {
$username = $user['username'];
}
$return_array[] = array($row['message'],$username);
}
return $return_array;
}
Can anyone understand what I am trying to do, and re-write my pseudo-code so that it doesn't use two '$this->'s and actually works?
I would really appreciate any help...
You simply need to change JOIN users to LEFT JOIN users.
Your current code performs an INNER JOIN, which produces result rows only when there are rows to join on both tables. A LEFT JOIN will produce results for all rows that exist on the left-hand-side table, substituting NULL for the values from the right-hand-side table when no corresponding rows exist there.
In your case, this means that you will be getting back rows for all messages, even if there is no corresponding user for some of them.
See also a visual explanation of SQL joins.

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work

Categories