This question already has an answer here:
Count always returns 1...but does it exist?
(1 answer)
Closed 3 years ago.
function c_save( $a, $status, $b ) {
global $db;
$st = $db->query( "select count(id) from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'" );
$count = $st->rowCount(); echo $count;
}
the echoed result - 1
Manually checking the table (20 rows total) - there is no such a row having cas = $a... so the result should be 0.
you are performing the count at the query level. the result of your query is a single line containing maybe 20.
if you want to get the number of records ', you can just get the value returned by the query or do not count within sql to get the full resultset and let php make the count.
Try this:
function c_save($a, $status, $b){
global $db;
$st = $db->query("select id from steps where cas = '" . $a . "' and status = '" . $status . "' and title = '" . $b . "'");
$count = $st->rowCount();
echo $count;
}
Related
I am trying to create an update that whenever the user gets an offer lower than the last day/week average price they get points for it 50 for last day and 20 for last week
I am desperate I have been trying for the longest time to chage thing on the proyect and now when I try to update that for every time the condition is met to update the db, it does its work and see when the price is cheaper and where it isnt but never increases the score which bugs me a lot¿can someone help?
function check_if_offer_cheaper_with_twenty_than_previous_day($prodname, $price)
// Check if the price found by the user is 20% lower than the most recent available average price of the previous day
{
global $db;
$sql = 'SELECT AVG(prices.price) >"' . $price / 0.8 . '" AS cheaper_than_previous_day'
. " FROM prices"
. ' WHERE prices.prodname = "' . $prodname . '"' .
' AND prices.date = CURDATE() - INTERVAL 1 DAY';
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
if (isset($row['cheaper_than_previous_day'])) {
$query = "UPDATE users SET total_score = total_score +50,
score_this_month = score_this_month + 50 WHERE id = '" . $_SESSION['user']['id'] . "'";
mysqli_query($db, $query);
return $row['cheaper_than_previous_day'];
} else {
return true;
}
}
function check_if_offer_cheaper_with_twenty_than_previous_week($prodname, $price)
// Check if the price found by the user is 20% lower than the most recent average price available in the previous week
{
global $db;
$sql = 'SELECT AVG(prices.price) > "' . $price / 0.8 . '" AS cheaper_than_previous_week'
. " FROM prices"
. ' WHERE prices.prodname = "' . $prodname .
'" AND prices.date BETWEEN CURDATE() - INTERVAL 8 DAY AND CURDATE() - INTERVAL 1 DAY';
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
if (isset($row['cheaper_than_previous_week'])) {
$query = "UPDATE users SET total_score = total_score +20, score_this_month = score_this_month +50
WHERE id = '" . $_SESSION['user']['id'] . "'";
mysqli_query($db, $query);
return $row['cheaper_than_previous_week'];
} else {
return true;
}
}
MySQL syntax uses commas to separate the assignment pairs, like this
$query = "UPDATE users SET total_score = total_score +20,
score_this_month = score_this_month +50
WHERE id = '" . $_SESSION['user']['id'] . "'";
dev.mysql 8.0 update syntax
That is assuming that $_SESSION['user']['id'] does not evaluate to null.
I'm making a poll, and I have a php script to get the percents of the number voted for that poll option. When i run a query I just keep getting 0 for the options. How can I make it so that each $val1 has a different number according to the row total in the database for?
For example: poll option 1 has 1 vote, poll option 2 has 1 vote, poll option 3 has 0 and poll option 4 has 0. and the query would output 50 option one and option 2 and 0 for option 3 and four.
My code
$poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
$option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");
while ($row = mysqli_fetch_array($option_sql)) {
$val1 = $row['total'];
}
$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");
$val2 = $poll_votess->num_rows;
$res = round ($val1 / $val2 * 100);
$options1 .= ' <script>
var doughnutData = [
{
value: ' . $res . ',
color:"#F7464A"
},
{
value : ' . $res . ',
color : "#46BFBD"
},
{
value : ' . $res . ',
color : "#FDB45C"
},
{
value : '. $res.',
color : "#949FB1"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>';
Database :
home_polls_vote: http://prntscr.com/2vd1lt
home_polls_option: http://prntscr.com/2vd1k7
In while loop you have took in $val1 just latest row value and because it is 0 votes, you got everywhere 0. You need to put it into array and later on use $res as array also so you can print different values down there in your script.
EDIT:
You can try something like this. First fetch total number of votes, then put percent in result in while loop.
$poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
$option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");
$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");
$number_of_votes= $poll_votess->num_rows;
while ($row = mysqli_fetch_array($option_sql)) {
$res[] = round ($row['total'] / $number_of_votes * 100);
}
$options1 .= '<script>
var doughnutData = [
{
value: ' . $res[0] . ',
color:"#F7464A"
},
{
value : ' . $res[1] . ',
color : "#46BFBD"
},
{
value : ' . $res[2] . ',
color : "#FDB45C"
},
{
value : '. $res[3].',
color : "#949FB1"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>';
Use mysql it'self for calculation this will avoid many lines of code and ease to process
http://dev.mysql.com/doc/refman/5.0/en/precision-math-rounding.html
https://dev.mysql.com/doc/refman/5.0/en/case.html
$sql = " SELECT ROUND(COUNT(hpv.id)/hpo.total * 100) AS res
FROM home_polls_option AS hpo
JOIN home_polls_vote AS hpv ON hpv.poll_id = hpo.poll_id
WHERE hpv.poll_id=$poll ['id']
GROUP BY hpo.value";
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I am trying to update a MySQL database field (decrease the value by 1) in a specific row (ID) of the "places" column, as long as the number in the field is greater than 0.
(see the example statement below)
UPDATE table SET places = places - 1 WHERE id = $id AND places > 0
The statement below fails apart from changing the value of the field to zero.
I would be grateful if anyone can help with the syntax error.
if($id){
global $modx;
$table = "`database_name`.`table_name`";
$update_seats = "`places` - 1";
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
return $result; // Returns 'true' on success, 'false' on failure.
}
You have enclosed new value of field in double quotes
$result = $modx->db->update( '`places` = "' . $update_seats . '"', $table, '`id` = "' . $id . '" AND `places` > 0' );
what is evaluated as string in MySQL query. Remove double quotes here
'`places` = "' . $update_seats . '"'
so that it looks like this
$result = $modx->db->update( '`places` = ' . $update_seats, $table, '`id` = "' . $id . '" AND `places` > 0' );
The query looks ok, if you need to set minimum value of 1 to places you should simply change the query accordingly:
UPDATE table SET places = places - 1 WHERE id = $id AND places > 1
I am trying to use the result of one mysql query in another mysql query, but I'm obviously doing something wrong. This is what I have:
<?php
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$panel = mysql_fetch_array($result);
?>
And then I want to use that in this bit:
<?php
if(!empty($_POST[p_length_mm]) && !empty($_POST[p_width_mm]) && !empty($_POST[p_aperture]))
{
$sql3="INSERT INTO estimateDescribesPanelProduct (estimate_no, panel_product_no, quantity)
VALUES ('$_GET[estimate_no]','$panel','$_POST[p_quantity]')";
if (!mysql_query($sql3,$con))
{
die('Error: ' . mysql_error());
}
}
?>
The query is basically working in that it is inserting the posted estimate_no and quantity into the DB, but not the correct panel_product_no (it just inserts '0'). How can I get it to insert the $result value?
P.S. I know that I should not be using mysql functions and I will not be in future, however I am so nearly finished with this project that at this point I am not in a position change.
Your are basicly copying content from one table to another.
Wy not use the MySQL INSERT .. SELECT syntax?
as #Dmitry Makovetskiyd wrote, mysql_fetch_array() returns a resource, not manipulatable results.
For example:
$result = mysql_query('SELECT panel_product_no
FROM panelProduct
WHERE length_mm = "' . ($_POST["p_length_mm"]) . '"
AND width_mm = "' . ($_POST["p_width_mm"]) . '"
AND veneer_type = "' . ($_POST["p_veneer"]) . '"
AND lipping = "' . ($_POST["p_lipping"]) . '"');
$resource = mysql_fetch_object($result);
You need to add in:
$panel = $resource->'panel_product_no';
You can then continue with your second query.
Note the change from mysql_fetch_array() to mysql_fetch_object() - as your query suggests you are only retrieving a singular value from the table (assuming there is only a singular panel with the specified length, width, veneer type and lipping), the object method will work fine.