How to use following simple query in code igniter format? - mysql

SET #rownum:=0;
SELECT #rownum:=#rownum+1 as count, student_name,student_info FROM studnet;
I want to merge this query in code igniter model...
I want output as follows where count is dynamic i.e. increases as record increases :::
count student_name student_info
1 Ram Palpa
2 Shyam Butwal

Using
CodeIgniter's Database Custom Function Calls:
Assuming you have mysqli set in your application/config/database.php:
$db['default']['dbdriver'] = 'mysqli';
Then in your model:
$this->load->database();
// Perform a mysqli_multi_query
$db_id = $this->db->conn_id;
$this->db->call_function("multi_query", $db_id, "SET #rownum:=0; SELECT #rownum:=#rownum+1 as count, student_name,student_info FROM student;"
$this->db->call_function('next_result', $db_id); // Skip the first query in this multi_query since you want the result from the second query
$result = $this->db->call_function("store_result", $db_id);
// Output each row
while($row = $result->fetch_assoc()){
$row['count'] . " ". $row['student_name'] . " " . $row['student_info'] . "\n";
}

Related

Writing mysql query with two variable conditions with prepare statement and bind param [duplicate]

I need to change this query to use a prepared statement. Is it possible?
The query:
$sql = "SELECT id, title, content, priority, date, delivery FROM tasks " . $op . " " . $title . " " . $content . " " . $priority . " " . $date . " " . $delivery . " ORDER BY " . $orderField . " " . $order . " " . $pagination . "";
Before the query, there's code to check the POST variables and change the content of variables in the query.
//For $op makes an INNER JOIN with or without IN clause depending on the content of a $_POST variable
$op = "INNER JOIN ... WHERE opID IN ('"$.opID."')";
//Or
$op = "INNER JOIN ... ";
//For $title (depends of $op):
$title = "WHERE title LIKE'%".$_POST["title"]."%'";
//Or
$title = "AND title LIKE'%".$_POST["title"]."%'";
//For $content:
$content = "AND content LIKE '%".$_POST["content"]."%'";
//For $priority just a switch:
$priority = "AND priority = DEPENDING_CASE";
//For $date and $delivery another switch
$d = date("Y-m-d", strtotime($_POST["date"]));
$date = "AND date >= '$d' 00:00:00 AND date <= '$d' 23:59:59";
//Or $date = "AND date >= '$d' 00:00:00";
//Or $date = "AND date <= '$d' 23:59:59";
//For $orderField
$orderField = $_POST["column"];
//For $order
$order= $_POST["order"];
//For $pagination
$pagination = "LIMIT ".$offset.",". $recordsPerPage;
How I could do this query using prepared statement?
The query could be more static but this means to make different prepared statements and execute it depending of $_POST checks.
It depends on many variables because this query show results in a table that contains search fields and column to order.
A full example of query would be like this (depending of $_POST checks):
SELECT id, title, content, priority, date, delivery FROM tasks INNER JOIN op ON task.op = op.opId WHERE op IN (4851,8965,78562) AND title LIKE '%PHT%' AND content LIKE '%%' AND priority = '2' ORDER BY date DESC LIMIT 0, 10
An excellent question. And thank you for moving to prepared statements. It seems that after all those years of struggle, the idea finally is starting to take over.
Disclaimer: there will be links to my own site because I am helping people with PHP for 20+ years and got an obsession with writing articles about most common issues.
Yes, it's perfectly possible. Check out my article, How to create a search filter for mysqli for the fully functional example.
For the WHERE part, all you need is to create two separate arrays - one containing query conditions with placeholders and one containing actual values for these placeholders, i.e:
WHERE clause
$conditions = [];
$parameters = [];
if (!empty($_POST["content"])) {
$conditions[] = 'content LIKE ?';
$parameters[] = '%'.$_POST['content ']."%";
}
and so on, for all search conditions.
Then you could implode all the conditions using AND string as a glue, and get a first-class WHERE clause:
if ($conditions)
{
$where .= " WHERE ".implode(" AND ", $conditions);
}
The routine is the same for all search conditions, but it will be a bit different for the IN() clause.
IN() clause
is a bit different as you will need more placeholders and more values to be added:
if (!empty($_POST["opID"])) {
$in = str_repeat('?,', count($array) - 1) . '?';
$conditions[] = "opID IN ($in)";
$parameters = array_merge($parameters, $_POST["opID"]);
}
this code will add as many ? placeholders to the IN() clause as many elements in the $_POST["opID"] and will add all those values to the $parameters array. The explanation can be found in the adjacent article in the same section on my site.
After you are done with WHERE clause, you can move to the rest of your query
ORDER BY clause
You cannot parameterize the order by clause, because field names and SQL keywords cannot be represented by a placeholder. And to tackle with this problem I beg you to use a whitelisting function I wrote for this exact purpose. With it you can make your ORDER BY clause 100% safe but perfectly flexible. All you need is to predefine an array with field names allowed in the order by clause:
$sortColumns = ["title","content","priority"]; // add your own
and then get safe values using this handy function:
$orderField = white_list($_POST["column"], $sortColumns, "Invalid column name");
$order = white_list($_POST["order"], ["ASC","DESC"], "Invalid ORDER BY direction");
this is a smart function, that covers three different scenarios
in case no values were provided (i.e. $_POST["column"] is empty) the first value from the white list will be used, so it serves as a default value
in case a correct value provided, it will be used in the query
in case an incorrect value is provided, then an error will be thrown.
LIMIT clause
LIMIT values are perfectly parameterized so you can just add them to the $parameters array:
$limit = "LIMIT ?, ?";
$parameters[] = $offset;
$parameters[] = $recordsPerPage;
The final assembly
In the end, your query will be something like this
$sql = "SELECT id, title, content, priority, date, delivery
FROM tasks INNER JOIN ... $where ORDER BY `$orderField` $order $limit";
And it can be executed using the following code
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
where $data is a conventional array contains all the rows returned by the query.

SQL SELECT CASE with Where From Looping Value

I have 2 tables :
table names transaction and detail customer
transaction table fields are idtrans and idcust.
detail customer fields are idcust and custname.
i have Problem with my php syntax, i want select table with condition from value lopping, here's my code:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from transaction";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sqlid="select * from detailcust where idcust='$row[idcust]')";
$resultid= $conn->query($sqlid);
if ($resultid->num_rows > 0){
while ($rowid= mysqli_fetch_array($resultid)){
$custname=$rowid["custname"];
echo $custname;
}
result name always first idcust value.
You seem to want the names of customer that have at least one transaction. If so, no need for loops and multiple queries. You can get the result you want with just one query:
select c.*
from detailcust c
where exists (select 1 from transaction t where t.idcust = c.idcust)

How to take values from one MySQl table, multiply them together, and put the results in another table

I have a table with 4 rows, I need to multiply col. 1 and 2 and put the results in col. 1 in the 2nd table. do the same with the other two cols' from table 1.
I'm sure its simple code. I just don't know MySQL
Get the values fetch the rows and insert again to the table 2:
$mysqli = new mysqli('127.0.0.1', 'tu_usuario', 'tu_contraseƱa', 'sakila');
if ($mysqli->connect_errno) {
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
$sql = "SELECT column1, column2 FROM table1";
if ($result = $mysqli->query($sql)) {
/* fetch object array */
while ($row = $result->fetch_row()){
$sql2 = "INSERT INTO table2 (col1) VALUES(".$row['column1']*$row['column2'].");";
$result = $mysqli->query($sql);
}
}
I didn't check if there is any error in theses code, it's just an example that shows the idea. I hope will be enough for you the explanation. If you still having doubts please answer again.

Joomla SQL query alternative

I have the following getListQuery() in my model. I want to add another join (see further) and was wondering if the level part could be done another way (without GROUP_CONCAT):
protected function getListQuery()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select(
$this->getState(
'list.select',
'a.id AS id,' .
'a.dbid AS dbid,' .
'a.alias AS alias,' .
'GROUP_CONCAT(DISTINCT l.level ORDER BY l.level ASC) as `levels`'
)
);
$query->from('#__maintable AS a');
$query->join('LEFT', '#__leveltable AS l ON l.dbid = a.dbid');
$query->group($db->quoteName('a.id'));
$query->order($db->escape($this->state->get('list.ordering', 'a.id') . ' ' . $db->escape($this->state->get('list.direction', 'ASC'))));
return $query;
}
In the leveltable there can be more then one row with a corresponding 'dbid'.
I would also like to add a second table which has a relation to 'dbid' which also can have multiple rows with the same 'dbid' and it has more fields I would require then just the 'level' field from leveltable.

How to get variables from MSQL query with WHERE IN clause

I have a couple of MySQL tables where I run a query on like this:
$sql = "
SELECT my_item
FROM t1
, t2
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
AND t1.spec = t2.spec
";
Note I am using the WHERE IN.
Next I run a query and use WHILE to try to get the results:
$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
}
This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.
How can I extract and store each of these three values in a separate variable each?
Thank you!
use join
SELECT my_item FROM t1 join t2
on t1.spec=t2.spec
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
or create array
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}
use this array likt that :-
foreach( $myitem as $myitems){
echo "My item is $myitems<br />\n";
}
or use indexing
echo "My item is $myitems[0]";
You can store the $row['my_item'] in an array.
Refer PHP arrays