I am trying to use the selected id's as an array a other statement. It seems it is not counting all the result as it is much lower that it is.. I have tried to find my answer on google but none of the options are working for me or i do not know how to use them in my case. There are no errors and i have error log on!
Here is my code, what am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid);
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
//echo print_r($counttheid);
//echo implode(',', $counttheid);
echo $sumcash;
I am no profesional developer just started learning this, any help is welcome!
Since you have edited the question, my original answer is no longer relevant.
I suggest for you to simplify your two queries into a single query. In your first query you select a bunch of ids and in the second query you sum a different value from the same table using the ids. You can just to that in one query:
SELECT SUM(mobcash) AS totalcash
FROM account
WHERE level <= '5'
AND door = ?
AND `group_name` = ?
AND betaald = 'Yes';
Original answer
You use $result->fetch_all(MYSQLI_ASSOC), meaning each row from the result set will be an associative array with the column names as the keys and the cell values as values. That is also the case, if you only select one column.
That means for this example table
id | name | balance
----+------+---------
1 | acc1 | 12.34
2 | acc2 | 1.23
your variable $dataid will have the following value (for the simplified query SELECT id FROM account):
$dataid = [
[
"id": 1
],
[
"id": 2
]
];
To get more familiar with PHP, you could write some foreach loops yourself, but you can also use the built-in PHP function array_column (php.net: array_column):
$ids = array_column($dataids, "id");
From an SQL perspective I would also suggest for you to learn about nested queries, since you could avoid this PHP logic altogether.
Related
Is there any way to order a database by a specific name stored in a function then random?
For example, if $name = 'Hasan' then I want the query to select Hasan row first then the other rows randomly
<?php
/* DATA BASE
id | Name
--------------+--------------------------------
'1' | Hasan
'2' | Ahmad
'3' | Majid
'4' | Hazem
*/
if(isset($_GET['name'])) {
$name = $_GET['name'];
}
else {
$name = 0;
}
$query = mysqli_query($con, "SELECT * FROM database ORDER BY $name, rand()");
?>
You can make a test on the name in the ORDER BY clause, sorting by whether it matches or not. You should use a prepared statement to protect yourself from SQL injection. For example:
$stmt = $con->prepare('SELECT * FROM database ORDER BY Name = ? DESC, rand()');
$stmt->bind_param('s', $_GET['name']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// ... do something
}
This works because MySQL treats boolean expressions as 0 (false) or 1 (true) in a numeric context, so the value of Name = $name will be 1 when the name matches and 0 otherwise, which you can then sort on descending.
Note that mysqli_stmt::get_result is only available with the mysqlnd native driver installed. Without that, you will need to use mysqli_stmt::bind_result, mysqli_stmt::store_result and mysqli_stmt::fetch to get your data.
You should be using a prepared statement here, something along these lines:
SELECT *
FROM database
ORDER BY name != ?;
Assuming you bound Hasan to the ? placeholder, this would give:
SELECT *
FROM database
ORDER BY name != 'Hasan';
This would place all Hasan records first (since false evaluates to 0), with all non Hasan records appearing after that. Note that your second sort level RAND() may not even be necessary, since MySQL does not guarantee any further default sorting order.
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 am looking for a way to increment and decrement by a step of three records in a table and return them.
Say ID '4' is currently active. I want to get the next 3 and the previous 3 records with IDs and category of 3.2.1 and 5.6.7 (via incrementing and decrementing).
So far I have:
$stmt = $db->query("SELECT id, category FROM test");
$stmt->execute();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$current = $results['id'];
$category = $results['category'];
$next = array(array(
'slide_no' => $current,
'category' => $category
));
}
print_r($next);
Using this, I am getting back every row in the table.
I'm getting confused how to increment and decrement the records by a step of 3 and make sure that the category will also increment accordingly.
Thank you very much.
You will need to create a string with the 6 ids that you need.
So if CatID was 4 you would want
$selectIDs = '1, 2, 3, 4, 5, 6, 7";
Then when you perform your SQl you would use
"SELECT id, category FROM test WHERE id IN (" . $selectIDs ."')";
If I understand your question correctly, you want to paginate the displayed data. You need to use the MySQL LIMIT clause.
You'll need to adjust your query, using values generated from your code. See an example below:
$stmt = $db->query("SELECT id, category FROM test LIMIT ?, 3");
#you'll supply the ? parameter depending on your current start index
MySQL Limit clause Tutorial
You can use the => and <= operators.
First store the id in a variable:
$intId = 4
Then add and decrement 3
$intAdd = $intId + 3
$intDecr = $intId -3
Then setup your sql string
$stmt = $db->query('SELECT id, category FROM test where id =>'. $intDecr.' and <= '.$intAdd. ');
I'm curious if I'll have to roll my own or if there's a pre-made PHP SQL library that I'm overlooking whereby I can pass in a sql select query and have it give me back a JSON object (or String) as a result.
In pseudo code what I want is this:
$startIndex = 0;
$myJSON = magicSqlToJSON("select first_name, last_name, phone, (select count(id) from users) as total from users limit $startIndex, 2");
$myJSON is now:
{"users":[
{"first_name":"Peter", "last_name":"O'Tool","phone":"1234567890","total":"100"},
{"first_name":"Gary", "last_name":"Shandling","phone":"1234567890","total":"100"}
]}
I know it wouldn't take very long to write this myself, but I kind of figured that this is just too common a need that it wouldn't already exist.
There is no single function that exists natively in PHP
However, you could do this quite quickly using a combination of mysqli_fetch_array() (for example) and json_encode(). You'd likely have to tweak the parent format slightly (i.e. underneath "users")
PHP
PHP has the json_encode() and json_decode() functions for this purpose, but you would need to manually loop over your data with a foreach or similar.
MySQL
You can make use of a User Defined Function such as lib_mysqludf_json, which would allow you return a JSON array from a query like so:
select json_array(
customer_id
, first_name
, last_name
, last_update
) as customer
from customer
where customer_id =1;
Yields this result:
+------------------------------------------+
| customer |
+------------------------------------------+
| [1,"MARY","SMITH","2006-02-15 04:57:20"] |
+------------------------------------------+
There is also a json_object function in that UDF, which should give you a very close representation of the sample in your question.
There is no direct function but yo can do something else :
The result are coming from an array so just call
json_encode(array); -> http://php.net/manual/en/function.json-encode.php
On it and that's it
Example:
$query = "select first_name, last_name, phone, (select count(id) from users) as total from users limit $startIndex, 2";
$result = mysql_query($query) or die(mysql_error());
echo json_encode(mysql_fetch_array($result));
Ill assume you use PDO
echo json_encode($pdo->exec($sql)->fetchAll());
otherwise, the general pattern is
$handle = execute_query($sql);
$rows = array();
while ($row = get_row_assoc($handle)) {
$rows[] = $row;
}
echo json_encode($rows);
I have the following query.
$query_assignments = "SELECT * FROM tb_scheduler_assignments
WHERE company_id = '".$company_id."' OR
dept_id = '".$dept_id."' OR
user_id = '".$user_id."' ORDER BY
due_date GROUP BY purchase_id";
What I'd like is a single query solution that would keep the results for user_id over dept_id and dept_id over company_id.
For example:
if the same purchase_id occurs for
rows that were gotten via dept_id and
user_id, then I only want the result
for the user_id;
if the same purchase_id occurs for
rows that were gotten via company_id
and user_id, then I only want the
result for the user_id
First, you're interpolating variables in your SQL, which suggests you might be vulnerable to SQL injection. Just to make sure. PHP should offer prepared statements, or some escaping function.
Second, your SQL statement won't compile because you're using GROUP BY a but selecting * which includes at least three more columns.
Third, it sounds like you're misunderstanding SQL in thinking that it might, in a query such as you're trying to formulate (without UNION ALL), retrieve duplicate rows, i.e. the same row multiple times because it matches multiple criteria. This is not so.
The "single query" solution that I was looking for doesn't seem to exist, or if it does, it would be way slower than just handling all the sorting in php.
So, I ran 3 separate queries, put each of them into arrays, and then in order to put them all into a final array with the hierarchy that I needed, I did the loops below to see if the purchaseID existed for the levels up the hierarchy. If it didn't, then I put it in to the array.
$finalArray = array();
foreach ($companyArray as $purchaseID => $companyData) {
if (empty($deptArray[$purchaseID]) && empty($userArray[$purchaseID])) {
$finalArray[] = $companyData;
}
}
foreach ($deptArray as $purchaseID => $deptData) {
if (empty($userArray[$purchaseID])) {
$finalArray[] = $deptData;
}
}
foreach ($userArray as $purchaseID => $userData) {
$finalArray[] = $userData;
}
Then I can sort that array however I want and loop through that to echo what I need to.
Not sure if that's the best way, but it worked well and is lightning fast for me.
$query_assignments = "SELECT *,
IF(user_id = {$user_id}, 30,
IF(dept_id = {$dept_id}, 20,
IF(company_id = {$company_id}, 10, 0)
)
) as priority
FROM tb_scheduler_assignments
WHERE company_id = {$company_id} OR
dept_id = {$dept_id} OR
user_id = {$user_id}
GROUP BY purchase_id
ORDER BY due_date, priority DESC";
You can make a virtual field with the if statement.
user_id: 30 pts
dept_id: 20 pts
company_id: 10 pts
else: 0 pts
WARNING: can not be Indexed!
Syntax FIX: GROUP BY and ORDER BY reordered