This is what i have:
$stmt = $handler->prepare('SELECT id FROM users');
$stmt->execute();
$id = $handler->lastInsertId();
echo $id;
So, i want result to be for example "There is $id registered users".
You never need to select the "last id" from a table. Every time you think you you need it, you need something else. For example, whatever "Last id" has nothing to do with the number of users registered. Instead, you have to count users:
$count = $handler->query('SELECT count(id) FROM users')->fetchColumn();
echo "There is $count registered users";
PDO::lastInsertId -- Returns the ID of the last inserted row or sequence value.
— https://secure.php.net/manual/en/pdo.lastinsertid.php.
What you want is a count of registered users, see Row count with PDO.
To retrieve the last inserted ID or sequence value see PDO get the last ID inserted.
Related
I am creating a page that displays info on equipment that has been scanned into and out of my office. The way I want it to display is
Equipment Name User(Headtech) Event used Returned(Y/N)
The problem is the SQL tables are everywhere and joining them all is proving to be difficult. There needs to be a chain going through three tables to get the Head tech name, this was not of my design and I can not change it.
What I currently have
$select = mysqli_query($con, "SELECT *
FROM equipment
JOIN pay
ON pay.eventid = equipment.eventid
JOIN personnel
ON personnel.workerid = (pay.eventid WHERE role = 'aht')
JOIN events
ON events.id = equipment.eventid
WHERE status='3'
ORDER By timeOut DESC");
while($row = mysqli_fetch_array($select)) {
$name = $row['name'];
$timeIn = $row['timeIn'];
$timeOut = $row['timeOut'];
$eventID = $row['eventid'];
echo "<div><div class='rowBoxS'>$name</div>";
$htName = $row['personnel.first'] . " " . $row['perosnnel.last'];
echo "<div class='rowBoxS'>$htName</div>";
$event = $row['eventName'];
echo "<div class='rowBoxS'>$event</div>";
if ($timeOut > 0){
echo "<div class='rowBoxS'>$</div></div>";
}
else{
echo "<div class='rowBoxS'>Failed to return</div></div>";
}
This is clearly not working as intended, and I'm very aware that that is probably not how joining works especially with the pay.eventid WHERE role = 'aht' bit. I want to know if there is a proper way to approach this. I tried looking it up, but most people probably have clean databases they are working with and couldn't possibly run into this problem.
Edit:
All the tables are on the same server. The problem is if I want to get someone's name you need to use the eventid row from equipment on the pay table find that id, then through the 'role' row find the user with AHT role and then take that persons workerid into the personnel table where you can finally find the persons name.
I'm using laravel 4.2 and I have the following table that looks like this
ID|chosen(boolean('0','1'))|subject|user_id
1|1 |cricket|2
2|0 |cricket|3
3|1 |rugby |2
I would like to choose the user_id that has the most chosen rows or in other words the user that has the most 1s in their chosen column. So in this case user 2 would be the correct result.
I believe this is the answer
$table = DB::table('tablename')
->select(array(DB::raw('count(user_id) AS CountUser')))
->where('chosen', 1)
->orderBy('CountUser', 'desc')
->groupBy('user_id')
->first();
however how do I display the user_id in my view? For example:
{{$table->user_id}} //should give me '2'
Error message reads:
Undefined property: stdClass::$user_id
You are selecting the count only. Try this
$table = DB::table('tablename')
->select(DB::raw('count(user_id) AS CountUser, user_id'))
->where('chosen', 1)
->orderBy('CountUser', 'desc')
->groupBy('user_id')
->first();
I have the following table structure :
Artists
id
name
picture
Entry
id
dj_id
producer_id
dj_id and producer_id field in most cases won't be the same, but it might happen. So I've set both field to be foreign keys on the artists_id field.
So in my Entry model, I have this function :
public function dj()
{
return $this->hasOne('Artist', 'id', 'dj_id');
}
This doesn't really work. It keeps returning the artist with id "1" even if the dj_id equals "5". Code sample :
$test = Entry::find(1);
var_dump($test->dj_id); // shows 5
var_dump($test->dj->id); // shows 1
What am I doing wrong ?
Ok so I figured it out, I had to change my dj relation to
return $this->belongsTo('Artist', 'dj_id', 'id');
Let's say I do a simple query:
$products =
Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('products')
->limit(9)
->queryAll();
Let's say there are 500 products in the database. Is there a way I can get YII to automatically return the total number (count) of products if the "limit" was included? Perhaps return an object like this:
$products->products = array( ... products ... )
$products->totalProducts = 500;
The problem is, if LIMIT is included, it will return items, and the count will therefore be 9. I want a solution whereby it will return the 9 items, but also the count of say 200 items if there were 200 items.
Why not an easy:
$сount = Yii::app()->db->createCommand('select count(*) from table')->queryScalar();
echo $count;
You'll either have to run two queries (a count(*) query without the limit and then the limited query) or you can send you can retrieve your products using CSqlDataProvider and let it do it for you. But it generally takes two queries.
Note: one of the nifty features in Yii 1.1.13 is that you can send your query builder command in to the CSqlDataProvider if you're going to be using a dataprovider. More information at on this pull request that fixed it. That way, you can both use the power of query builder while also being able to shift your data into a dataprovider. Previously you had to build your SQL statement manually or grab the queryText of the command.
Yii::app()->db->createCommand('select count(*) from tbl_table')->queryScalar();
Try to use execute() instead of query() because execute returns rows count.
example:
$rowCount = $command->execute();
You could try using COUNT like this:
$dbCommand = Yii::app()->db->createCommand("
SELECT COUNT(*) as count FROM `products`");
$data = $dbCommand->queryAll();
Hope that helps!
EDIT: You might find this useful too: CDataProvider
Try this -
$sql = Yii::app()->db->createCommand('select * from tbl_table')->queryAll(); //It's return the Array
echo count($sql); //Now using count() method we can count the array.
I have a mails table which is my main tables for manipulating mails. I also have mails_sent and mails_dates which has FK connecting them with mails and contain data as follows mails_dates - a single mail could have more than one date set for sending so I have realtion 1:N where N are all the dates set from the user for the mail to be send and mails_sent - after a mail is sent a new record is added in this table with the id of the mail and the date it was sent. Because as I mentioned a mail could be sent more than once here the relation is also 1:N where N here represents the different dates when a mail was sent.
I need to show this info in a UI. First I had to show only the sending dates and I user this:
$this->db->select("mails.id, mails.subject, mails.dt_created, mails.groups");
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_dates.dt_sending_date, '%d-%m-%Y')) AS sending_dates", FALSE );
$this->db->join('mails_dates','mails_dates.mail_id = mails.id', 'left');
$this->db->join('mails_sent','mails_sent.mail_id = mails.id', 'left');
$this->db->from('mails');
$this->db->group_by('mails.id');
$res = $this->db->get()->result_array();
return $res;
When I was using this everything was fine I was getting a string with all the dates in it. But the problem is when I try to get the dates when a mail was sent. I added one more select:
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_sent.dt_sent, '%d-%m-%Y')) AS sent_dates", FALSE );
making my query looks like this:
$this->db->select("mails.id, mails.subject, mails.dt_created, mails.groups");
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_sent.dt_sent, '%d-%m-%Y')) AS sent_dates", FALSE );
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_dates.dt_sending_date, '%d-%m-%Y')) AS sending_dates", FALSE );
$this->db->join('mails_dates','mails_dates.mail_id = mails.id', 'left');
$this->db->join('mails_sent','mails_sent.mail_id = mails.id', 'left');
$this->db->from('mails');
$this->db->group_by('mails.id');
$res = $this->db->get()->result_array();
return $res;
But the problem is that If sending_dates contains let's say - 6 values, and sent_dates has only one I end up with a string containing 6 times the value of sent_dates. This is in production so I don't have a lot of records but the same happens with a query where I have 2 sending_dates and 1 record for sent_dates still I get 2 times the record from sent_dates.
How can I fix this?
Thanks
Leron
Ok, I found the solution, here it is:
$this->db->select("GROUP_CONCAT(DISTINCT(DATE_FORMAT(mails_sent.dt_sent, '%d-%m-%Y'))) AS sent_dates", FALSE );
In other words just use DISTINCT.