id state
1 1
2 0
5 1
4 0
7 1
I want first remove all state=0 form my result. and then return row number of target record.
for example for id='7' it must return me 3
how can I do it with mysqli/php?
this is false but something like this:
function getLogs($itime = 0,$count = null)
{
$conn = $this->connectDB();
$sql = "SELECT num_rows() FROM Content Where id='22' and $state=0 ORDER BY id ASC";
$rows = mysqli_fetch_all($conn->query($sql), MYSQLI_ASSOC);
$this->disconnectDB($conn);
return num_rows();
}
This is probably simpler and you can replace 22 with a variable.
SELECT COUNT(id) FROM Content WHERE id <= 22 AND state != 0
In your example you put 22 in quotes, but your id isn't a string is it? Plus in addition to the comment above about $state = 0, it should be state not $state
Related
I have an SQL table of students with one subject. I would like to take the mean of all the students for this particular subject such that:
Sum of the subject/Number of total students
The table looks like this:
Student ID : 1
=============
Maths : 40
Student ID : 2
=============
Maths : 60
Student ID : 3
=============
Maths : 90
Student ID : 4
=============
Maths : 0
So if the student has scored 0, then ignore this student and its score in calculating the mean.
<?php
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$db = new PDO("mysql:host=localhost; dbname=db;charset=utf8",'user','');
$sql = "SELECT * FROM Students";
$stmt = $db->query($sql);
while($data = $stmt->fetch(PDO::FETCH_OBJ)){
//How to take the mean of 1 subject for all students?
}
?>
Fix this line first so that...you can only get scores greater that 0
$sql = "SELECT * FROM students WHERE subjectscore > 0"; //assuming your column for scores is "subjectscore"
The the rest of the code to get mean should be
$stmt = $db->query($sql);
while($data = $stmt->fetch(PDO::FETCH_OBJ)){
$sumparts .= $data->subjectscore."+"; //Add a delimiter after every returned obj
}
print_r($sumparts); //For debug :to see which ones are selected
$sumarr = explode("+",$sumparts); // Convert the delimited string to array
$sum = array_sum($sumarr); //Get sum of values of array in this case the scores
$divisor = count($sumarr) - 1; //The minus 1 is necessary since well the delimited string will always have 1 extra key therefore making the count to count 1 more unnnecessary key
$total = $sum/$divisor; //Sum of all divided by the total number of objects
echo $total;
I'm trying to distribute an amount proportionately to each row of a table based on the value of a column, 'value' and it's percentage of the sum of that column for all rows. For example
AmounttoDistribute = 200
CurrentTotal = 100
Row 1 value = 25
Row 2 Value = 50
Row 3 Value = 15
Row 4 Value = 10
I want to make it where
Row 1 will receive 50
Row 2 will receive 100
Row 3 will receive 30
Row 4 will receive 20
I've tried a couple different while loops but so far the results are very different than what I'm trying to achieve. I've already got the $AmounttoDistribute and $SumofValue in variables which I know to be correct. Here's what I've tried:
$val = mysqli_query($db, "SELECT Value FROM Table WHERE columnX = 1 AND columnY = 1");
$Result = mysqli_fetch_array($val);
$value = $Result['Value'];
while($Result = mysqli_fetch_array($val)){
mysqli_query($db, "UPDATE Table SET Value = Value + (Value / $SumofValue * $AmounttoDistribute) WHERE columnX = 1 AND columnY = 1");
I've also tried the while loop below where I already have a variable for AmounttoDistribute divided by SumofValue, ($AmountPerEach1):
$val = mysqli_query($db, "SELECT Value FROM Table WHERE columnX = 1 AND columnY = 1");
$Result = mysqli_fetch_array($val);
$value = $Result['Value'];
while($Result = mysqli_fetch_array($val)){
mysqli_query($db, "UPDATE Table SET Value = Value + (Value * $AmountPerEach1) WHERE columnX = 1 AND columnY = 1");
Thanks for any help
If you know the AmountToDistribute and CurrentTotal, you can do this via one simple SQL statement.
Basically:
UPDATE table SET column = column + ((AmountToDistribute/CurrentTotal)*column);
Specifically for this case:
UPDATE Table SET Value = Value + 2*Value;
I can't figure-it out how to count all these dancers columns and echo with total of all dancers
id | dancer1 | dancer2 | dancer3 | dancer4, and so on..
---------------------------------------
1 alex michael dalm name
2 clare rose test
I have this for the start but is not working:
$counter = mysql_query("SELECT COUNT(*) AS id FROM table");
$num = mysql_fetch_array($counter);
$dancers = $num["id"];
echo "Total dancers: $dancers";
Any help is appreciated. Thanks!
Try this:
$counter = mysql_query("SELECT * FROM table");
$dancers = 0;
while($rows = mysql_fetch_array($counter)){
for($i = 1; $i <= 24; $i++){
$dan_id = 'dancer'.$i;
if($rows[$dan_id] != "" || $rows[$dan_id] != null )
$dancers++;
}
}
echo "Total dancers:". $dancers;
Note: Never design your database table like this.
I would actually save your dancers in a different (easier) way... For examle:
ID NAME SURNAME PHONE ....
1 Anna Brickstone 0975 ...
2 Jef Damen 0754 ...
That way you could use the following code to count tables:
$dancersCount="0";
$sql = "SELECT * FROM dancers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dancersCount++;
}
} else {
echo "No dancers..";
}
echo"$dancersCount";
The counter will count +1 each time it finds a row (dancer)
If you really want to do it that way...
Then I don't really think there's an easy way to fix this... You will probably need to check how many columns you have in your database but that's not something i can help you with...
You need to change your table structure:
id | dancerNumber | name
1 1 alex
2 1 clare
3 2 michael
4 2 rose
5 3 dalm
6 3 test
7 4 name
8 4 dana
SELECT COUNT(*) AS id FROM table will return 8 dancers. If this is what you were looking for?
if you want to keep your structure then you need to do the following sql query
SELECT dancer1,
dancer2,
dancer3,
(CASE WHEN (dancer1 <> "" AND dancer1 IS NOT NULL) THEN 1 ELSE 0 END +
CASE WHEN (dancer2 <> "" AND dancer2 IS NOT NULL) THEN 1 ELSE 0 END +
CASE WHEN (dancer3 <> "" AND dancer3 IS NOT NULL) THEN 1 ELSE 0 END) AS COUNTER
FROM table
This will count all the non empty and non null columns and add a counter at the end of the table. this counter will then contain the number of dancers with your structure.
Full answer with your php code
$query = 'SELECT (CASE WHEN (dancer1 <> "" AND dancer1 IS NOT NULL) THEN 1 ELSE 0 END +
CASE WHEN (dancer2 <> "" AND dancer2 IS NOT NULL) THEN 1 ELSE 0 END +
CASE WHEN (dancer3 <> "" AND dancer3 IS NOT NULL) THEN 1 ELSE 0 END) AS COUNTER
FROM table'
$counter = mysql_query($query);
$num = mysql_fetch_array($counter);
$dancers = $num["COUNTER"];
echo "Total dancers: $dancers";
I have a function in php I use it for paging it is like this :
$query = "SELECT id,
FROM table
ORDER BY id ASC
LIMIT $offset,5";
this work fine but what I want is to get the page that contain id number let say 10 and with it the other 4 rows, I want it to return something like this:
7,8,9,10,11,12 -> if I give it id number 10.
25,26,27,28,29 -> if I give it id number 26 and so on.
like it would return the 5 rows but I want to know how to set the offset that will get me
the page that have the 5 rows with the specified id included.
what should I do like adding where clause or something to get what I want!
Notice that the IDs in your table won't be consecutive if you delete some rows. The code below should work in such conditions:
$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);
$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Try something like this
//but for pagination to work $page should be $page*$limit, so new rows will come to your page
$limit = 5;
$start = ($page*limit) -2; // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values
$query = "SELECT id,
FROM rowa
ORDER BY id ASC
LIMIT $start,$limit";
I have a problem, it may be a simple fix to the issue, but I can't seem to figure it out. I am new to PHP and MySQL, so I'm reading everything everywhere, but lack of experience is very frustrating, as often times it takes ages to realize a small error. Please look at the following tables and read below the questions.
The PHP/mysql is in Joomla environment, I am trying to modify a plugin, so that is updates with values from different tables into a set of other tables, that were not originally intended, but all tables reside in the same database.
Table 1 vm_orders
---------------------------------------------
order_id user_id
---------------------------------------------
20 1
55 6
65 2
30 4
50 67
Table 2 vm_order_item
---------------------------------------------
order_item_id order_id order_item_sku
---------------------------------------------
20 20 1
55 55 35
65 65 60
30 30 22
50 50 3
Table 3 xipt_ users
---------------------------------------------------
userid Profiletype template
----------------------------------------------------
1 1 default
6 3 default
2 1 default
4 8 default
67 7 default
Table 4 community_fields_values
---------------------------------------------
id user_id field_id value
---------------------------------------------
1 1 55 Female
2 6 35 Cat
3 2 2 2
4 4 18 Texas
5 67 12 bike
What I need to is first of all get the order number according to the user that has place the order.
The userid variable is being passed from elsewhere in the script. That part is working fine.
So the user 67 has placed an order. These are the things I want to achieve.
Query 1: I want to get the "orderid" value from "order_id" column of vm_orders table (table 1); i will call the result "vmorderid" and use it in another query.
Query 2: Using the "vmorderid" from query 1 as the order_id value in the "order_id" column of vm_order_item table (table 2).
I want to get the order_item_sku value from the "order_item_sku" column of my_order_item table (table 2).
I will call the result "vmsku" and use it in another query.
Query 3: Using the "vmsku" from query 2 as the profiletype value in the "Profiletype" column of vm_users table (table 3).
I want to UPDATE the value of the "profiletype" column, with "vmsku" value.
Query 4: Using the "vmsku" from query 2 as the value in the "value" column of community_fields_values (table 4).
I want to UPDATE the value of the "value" column in my_fields_values (table 4) "vmsku" value.
Okay, I hope you are with me so far, I have tried a couple of queries, but it's not working.
Here is what I have so far:
Assuming the user it is being passed from a param field.
$userid = $this->params->get('userid', 'defaultValue');
function _vm_custom_order($vmorderId)
{
$vmorderId = $database->loadResult();
$database = JFactory::getDBO();
// query the db to see if the user is already a member of group
$vmorderId ="
SELECT MAX
`order_id`
FROM
#__vm_orders';
WHERE
`user_id` = '{$userid}'
";
$database->setQuery( $vmorderId );
$data = $database->loadResult();
return $data;
}
function _vm_sku($vmsku)
{
$vmsku = $database->loadResult();
$database = JFactory::getDBO();
// query the db to see if the user is already a member of group
$vmsku = "
SELECT
`product_sku`
FROM
#__vm_order_item';
WHERE
`order_id` = '{$vmorderId}'
";
$database->setQuery( $vmsku );
$data = $database->loadResult();
return $data;
}
function _add( $userid, $groupid, $vmsku)
{
$success = false;
$database = JFactory::getDBO();
if (!$allow_multiplegroups = $this->params->get( 'allow_multiplegroups', '1' )) {
// query the db to see if the user is already a member of ANY group
$database->setQuery("
SELECT
`profiletype`
FROM
#__xipt_users
WHERE
`userid` = '{$userid}'
");
$member = $database->loadResult();
// if so, do not execute
if (intval($member) > 0) {
return $success;
}
}
$already = plgAmbrasubsAddToXipt::_already( $userid, $groupid );
if (($already != $userid))
{
$database->setQuery("
SELECT MAX
`order_id`
FROM
#__vm_orders
WHERE
`user_id` = '{$userid}'
");
$vmorderId = $database->loadResult();
if ($database->query()) {
$success = true;
}
}
if (($already != $userid))
{
$database->setQuery("
SELECT
`product_sku`
FROM
#__vm_order_item
WHERE
`order_id` = '{$vmorderId}'
");
$vmsku = $database->loadResult();
if ($database->query()) {
$success = true;
}
}
// if they aren't already a member of the group, add them to the group
if (($already != $userid))
{
$database->setQuery("
UPDATE
#__xipt_users
SET
`profiletype` = '{$vmsku}'
WHERE
`userid` = '{$userid}'
LIMIT 1
");
if ($database->query()) {
$success = true;
}
}
return $success;
}
}
I also tried it this way:
function _add( $userid, $groupid, $vmsku)
{
$success = false;
$database = JFactory::getDBO();
if (!$allow_multiplegroups = $this->params->get( 'allow_multiplegroups', '1' )) {
// query the db to see if the user is already a member of ANY group
$database->setQuery("
SELECT
`profiletype`
FROM
#__xipt_users
WHERE
`userid` = '{$userid}'
");
$member = $database->loadResult();
// if so, do not execute
if (intval($member) > 0) {
return $success;
}
}
$already = plgAmbrasubsAddToXipt::_already( $userid, $groupid );
if (($already != $userid))
{
$database->setQuery("
SELECT MAX
`order_id`
FROM
#__vm_orders
WHERE
`user_id` = '{$userid}'
");
$vmorderId = $database->loadResult();
if ($database->query()) {
$success = true;
}
}
if (($already != $userid))
{
$database->setQuery("
SELECT
`product_sku`
FROM
#__vm_order_item
WHERE
`order_id` = '{$vmorderId}'
");
$vmsku = $database->loadResult();
if ($database->query()) {
$success = true;
}
}
// if they aren't already a member of the group, add them to the group
if (($already != $userid))
{
$database->setQuery("
UPDATE
#__xipt_users
SET
`profiletype` = '{$vmsku}'
WHERE
`userid` = '{$userid}'
LIMIT 1
");
if ($database->query()) {
$success = true;
}
}
return $success;
}
}
EDIT: I have now tried as suggested, to use JOIN to accomplish the task, so far no joy!
UPDATE
#__xipt_users
SET
`profiletype.#__xipt_users` = `product_sku.#__vmsku`
WHERE
`userid` = '{$userid}'
AND
(
SELECT `order_id.#__vm_orders`
FROM #__vm_orders, #__vm_order_item
LEFT JOIN #__vm_orders
ON #__vm_orders.`order_id` = #__vm_order_item.`order_id`
ORDER BY `order_id.#__vm_order` DESC LIMIT 1
WHERE
`user_id.#__vm_orders` = '{$userid}'
) AS #__vmorder_id
SELECT ` product_sku.#__vm_order_item`
FROM #__vm_order_item, #__vmorder_id
LEFT JOIN #__vm_order_item
ON `#__vm_order_item.order_id` = `#__vmorder_id.order_id`
WHERE
`order_id.#__vm_order_item` = `order_id.#__vmorder_id`
)
AS #__vmsku
LIMIT 1
");
Join Statements
I would suggest you start learning how to create Join Statements in MySQL.
Have a look at this website:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
That way you are able to combine multiple queries into one. It will make this job a lot easier!
Piece of paper
Also it will help you to draw your database on a piece of paper to get a better overview of what you want to do. For example you can draw lines between the table fields you want to link.