I'm using CakePHP 3, I need to run a raw SQL query on multiple tables. In CakePHP 2, this could be done by using the query() method on any model ( $this->Messages->query("select..") ).
I need the method that allows me to run a SQL query in CakePHP 3. Following is the code snippet I'm using:
$aumTable = TableRegistry::get('Messages');
$sql = "SELECT (SELECT COUNT(*) FROM `messages`) AS `Total_Count`,
(SELECT COUNT(*) FROM `messages_output`) AS `Total_Output_Count`,
(SELECT COUNT(*) FROM `messages_output` WHERE `is_success`=1) AS `Total_Successful_Output_Count`,
(SELECT COUNT(*) FROM `messages_output` WHERE `is_success`=0) AS `Total_Error_Output_Count`,
(SELECT COUNT(*) FROM `users`) AS `Total_User_Count`;";
// to run this raw SQL query what method should i use? query() doesn't work..
// $result = $aumTable->query($sql); ??
// $result = $aumTable->sql($sql); ??
If you can provide links to CakePHP 3 model documentation where I can find this info, that would be helpful too. I tried searching on google but could only find questions related to CakePHP 2.
First you need to add the ConnectionManager:
use Cake\Datasource\ConnectionManager;
Then you need to get your connection like so:
// my_connection is defined in your database config
$conn = ConnectionManager::get('my_connection');
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#creating-connections-at-runtime
After that you can run a custom query like this:
$stmt = $conn->execute('UPDATE posts SET published = ? WHERE id = ?', [1, 2]);
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries
And then you are ready to fetch the row(s) like this:
// Read one row.
$row = $stmt->fetch('assoc');
// Read all rows.
$rows = $stmt->fetchAll('assoc');
// Read rows through iteration.
foreach ($rows as $row) {
// Do work
}
More info: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-fetching-rows
The documentation for this is here: http://book.cakephp.org/3.0/en/orm/database-basics.html#executing-queries
But what's not written there is how to execute it. Because it cost me a while, here is the solution for that:
1.You need to add
use Cake\Datasource\ConnectionManager;
2.init the ConnectionManager (as mentioned above)
$conn = ConnectionManager::get('my_connection');
3.Execute your SQL with something like this
$firstName = $conn->execute('SELECT firstname FROM users WHERE id = 1');
The question is already very old, but I still find it frequently.
Here is a solution for CAKEPHP 3.6 and (short) for newer PHP Versions.
It is not necessary to use the ConnectionManager get function and often it does not make sense, as the connection name may not be known at all. Every table has its / a connection which one can get with getConnection ().
If you are already in the Messages Table (src/Model/Table/MessagesTable.php), you can simply use the Connection
$con = $this->Messages->getConnection();
If you are not there (what your code would suggest with TableRegistry::get(), you can do that with this table as well
// $aumTable is declared in question
$con = $aumTable->getConnection();
then you can execute a RAW query as shown above:
$result = $con->execute ();
// short
$result = $this->Messages->getConnection()->execute ('Select * from ...')
// or ($aumTable is declared in question)
$result = $aumTable->getConnection()->execute ('Select * from ...');
Related
There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}
I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC
So I need to run a long(ish) query to insert a new row into a table, based on values of another row elsewhere in the database. This is running in Joomla 3.1.5
Typically, you can use MySql's INSERT .. SELECT syntax to easily do this, but I'm looking for a way to keep close to Joomla's query builder, example:
<?php
// ...
// Base Tables & Columns.
$my_table = '#__my_table';
$columns = array('column_one', 'column_two');
// Set up the database and query.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Escape / quote the table name.
$my_table = $db->quoteName($my_table);
// Escape all columns.
$cols = array_map(array($db, 'quoteName'), $cols);
$query
->insert($my_table)
->columns($columns)
// E.g. ->select( ... )->from( ... ) ...
$db->setQuery($query);
$result = $db->query();
// ...
?>
Of course, the example comment won't work, but I was wondering if there was a way which would allow me to perform something similar (without needing to run a separate query elsewhere).
Naturally, if there's no way to perform this type of query, I can just drop to using a raw query string.
The docblocks of many JDatabaseQuery methods include the following statement
* Note that you must not mix insert, update, delete and select method calls when building a query.
This is because ... to over simplify but as an example how would we know which list of columns (or which where clause etc) to put where when we are building the query.
But there are ways that you can get around this limitation by building your query in a slightly more complex way (which is fair since it's a more complex query). So for example
$db = JFactory::getDBO();
$queryselect = $db->getQuery(true);
$queryselect->select($db->quoteName(array('id','title','alias')))
->from($db->quoteName('#__content'));
$selectString = $queryselect->__toString();
$queryInsert = $db->getQuery(true);
$queryInsert->columns($db->quoteName(array('id','title','alias')))
->insert($db->quotename('#__newtable'));
$db->setQuery($queryInsert . $selectString);
$db->execute();
I'm an SQL noob and learning how to use PDO. I'm doing a course which introduces basic user login functions. In an example of a login page, they check the username/password against a MySQL database. I edited their code slightly to be able to simultaneously check whether the user/pass combo exists and also grab the user's first name:
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]));
// execute query
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$_SESSION["authenticated"] = true;
// get contents of "firstname" field from row 0 (our only row)
$firstname = mysql_result($result,0,"firstname");
if ($firstname != '')
$_SESSION["user"] = $firstname;
}
What I want to do is use SQLite instead and do the same thing. Searching around has only resulted in people saying you should use a SELECT COUNT(*) statement, but I don't want to have to use an extra query if it's possible. Since I'm SELECTing the firstname field, I should only get 1 row returned if the user exists and 0 if they don't. I want to be able to use that number to check if the login is correct.
So far I've got this:
$dsn = 'sqlite:../database/cs75.db';
$dbh = new PDO($dsn);
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
$_POST["username"],
$_POST["password"]);
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = sqlite_num_rows($result);
if ($rows == 1) { ...
But this is returning Warning: sqlite_num_rows() expects parameter 1 to be resource, object given.
Is there a way I can do this efficiently like in MySQL, or do I have to use a second query?
EDIT:
I found this, not sure if it's the best way but it seems to work: How to get the number of rows grouped by column?
This code let me do it without the second query:
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = $result->fetch(PDO::FETCH_NUM);
echo 'Found: ' . $rows[0];
$rows is an array so I can just count that to check if it's > 0.
Thanks to everyone who commented. I didn't know until now that there were 2 different approaches (procedural & object oriented) so that helped a lot.
Normally, you can use PDOStatement::rowCount(), however, SQLite v3 does not appear to provide rowcounts for queries.
You would need to seperately query the count(*), or create your own counting-query-function.
The documentation comments have an example of this
A bit late, but i tried this with SQLite3 successful:
$result = $db->query('SELECT * FROM table_xy');
$rows = $result->fetchAll();
echo count($rows);
Thanks for previous replies
I am execution "select Name from table_name where id=1"; . i saw some tutorials for getting data from the database, they mentioned $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
DB->setFetchMode(Zend_Db::FETCH_OBJ); and the result will getting through $result = $DB->fetchAssoc($sql); This $result is an array format, i want to get only name instead of getting all the data from the database. I am new to this topic. if i made any mistake pls do correct.
try this:
$result = $DB->fetchOne("SELECT name FROM table_name WHERE id=1");
This code will execute your query through doctrine getServiceLocator(). With the help of createQueryBuilder(), you can write your query directly into zend-framework2, and with setParameter, any desired condition would be set easily.
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$qb = $entityManager->createQueryBuilder();
$qb->select(array(
'TableName.columnName as columnName '
))
->from('ProjectName\Entity\TableName', 'TableName')
->where('TableName.TableId = :Info')
->setParameter('Info', $id);
$var= $qb->getQuery()->getScalarResult();
The $var variable holds the value for which, you wanted the comparison to be made with, and holds only the single values of your interest.