I'm trying to create a query in php that retrieves values from a database and multiplies them with user input. The user selects an item enters a number and I want the query to multiply the number with different values depending on the item that the user selected. For example, when the user selects an item from id 1 and enters a number, I want the query to retrieve values from id 1 multiply it with the number and if the user selects id 2, the number should be multiplied with values from id 2. Here's what I have so far.
$value = isset($_POST['selection']);
switch ($value){
case 1 :
$strSQL = "SELECT * FROM table1 WHERE id ='1' ";
$rs = mysql_query($strSQL);
while ($row = mysql_fetch_array($rs)) {
$q1 = $row['Rate_1' ];
$q2 = $row['Rate_2'];
}
$c1 = $input * $q1 ;
$c2 = $input * $q2 ;
$total = $c1 + $c2;
echo $total;
break; }
case 2 :
$strSQL = "SELECT * FROM table1 WHERE id ='2' ";
$rs = mysql_query($strSQL);
while ($row = mysql_fetch_array($rs)) {
$q1 = $row['Rate_1' ];
$q2 = $row['Rate_2'];
}
$c1 = $input * $q1 ;
$c2 = $input * $q2 ;
$total = $c1 + $c2;
echo $total;
break;
}
I have a form where the user enters a number but when I click calculate, it doesn't bring up any results.
You are closing your switch before it ends, https://eval.in/418432. Error reporting would have shown this. Aside from this you are running the same code twice. Might as well use the value in the query (note we cast the value as int, never pass user input direct to a query, this opens you to SQL injections, another approach with this driver is, http://php.net/manual/en/function.mysql-real-escape-string.php).
if(isset($_POST['selection']) && ($_POST['selection'] == 1 || $_POST['selection'] == 2)){
$id = (int)$_POST['selection'];
$strSQL = "SELECT * FROM table1 WHERE id = $id";
$rs = mysql_query($strSQL);
$row = mysql_fetch_array($rs); // id is auto-incrementing presumably so no need to loop, only 1 row
$q1 = $row['Rate_1' ];
$q2 = $row['Rate_2'];
$c1 = $input * $q1 ; //dont know where $input is defined but presuming you took care of that else where in the code
$c2 = $input * $q2 ;
$total = $c1 + $c2;
echo $total;
} else {
echo 'Invalid value passed in';// or do nothing here and take out the else.
}
It would also be best to update your db driver to mysqli or pdo which will allow you to use prepared statements.
Here's a thread on getting error messages,
How to get useful error messages in PHP?
and a thread on SQL injection prevention,
How can I prevent SQL injection in PHP?
Related
I'm looking to insert random numbers into each column in a database.
The issue that is occuring is that each column for some reason has the same random generated value being passed inside.
$sql = "SELECT * FROM players";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$targScore = 3;
while($row = $result->fetch_assoc()) {
$target = 3; // The target number the sequence is adding up to
$n = 4; // Max numbers within sequence
while ($n) {
if (1 < $n--) {
$addend = rand(0, $target - ($n - 1));
$target -= $addend;
$num[] = $addend;
} else {
$num[] = $target;
}
}
/* Rows to update */
/* Output looks like:
[0] = 1
[1] = 2
[0] = 0
[0] = 1
*/
$changeScore = "UPDATE players SET doja='$num[0]' WHERE score='$targScore'";
$conn->query($changeScore);
$changeScore = "UPDATE players SET 7acres='$num[1]' WHERE score='$targScore'";
$conn->query($changeScore);
$changeScore = "UPDATE players SET tweed='$num[2]' WHERE score='$targScore'";
$conn->query($changeScore);
$changeScore = "UPDATE players SET bickel='$num[3]' WHERE score='$targScore'";
$conn->query($changeScore);
}
}
The data looks like: https://imgur.com/a/nhhZDVo
What I need is that each loop, it will run the randomizer again but change the numbers its inserting so that each row will have different numbers.
You need to first get a list of all the rows that meet the score condition. Then you have to update them one by one, so you can set different random values in each.
$select_stmt = $conn->prepare("SELECT id FROM players WHERE score = ?");
$select_stmt->bind_param("i", $targScore);
$select_stmt->execute();
$res = $select_stmt->get_result();
$update_stmt = $conn->prepare("UPDATE players SET doja = ?, 7acres = ?, tweed = ?, bickel = ? WHERE id = ?");
$update_stmt->bind_param("iiiii", $doja, $acres, $tweed, $bickel, $id);
$target = 3;
while ($row = $res->fetch_assoc()) {
$n = 4;
$num = [];
while ($n) {
if (1 < $n--) {
$addend = rand(0, $target - ($n - 1));
$target -= $addend;
$num[] = $addend;
} else {
$num[] = $target;
}
}
[$doja, $acres, $tweed, $bickel] = $num;
$id = $row['id'];
$update_stmt->execute();
}
There's also no need to use four UPDATE statements to update 4 columns in the same rows.
MySQL has a rand() function https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_rand
(Note the warning that it's not perfectly random / security secure, but nor is PHPs rand()).
If you do not need to know what the values are, you can simply do UPDATE myCol=FLOOR(RAND() * 200) WHERE myConditionalField=MyCondition
This will allocate a random number from 0 to 199; examples in the MySQL manual (linked above) as to how to set a range, e.g. FLOOR(7 + (RAND() * 5)) gives an integer from 7 to 11.
I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;
Hello this code works but currently it is very repetitive.
I have been trying for a few days now, and I just cannot work out how to rewrite these separate SELECTs into one loop using arrays.
I would like to push about 20 entries, so if I cannot work out how to do the loop then its going to messy! :(
I would be grateful for any help with the first loop and from that I will try and solve the rest myself from that advice, Thanks..
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select data from table from a random row
$grab1 = "select * from stock_tbl where stock_id='$ran_num[0]'";
$grab2 = "select * from stock_tbl where stock_id='$ran_num[1]'";
$grab3 = "select * from stock_tbl where stock_id='$ran_num[2]'";
$grab4 = "select * from stock_tbl where stock_id='$ran_num[3]'";
$grab5 = "select * from stock_tbl where stock_id='$ran_num[4]'";
$grab6 = "select * from stock_tbl where stock_id='$ran_num[5]'";
$result1 = $mysqli->query($grab1);
$result2 = $mysqli->query($grab2);
$result3 = $mysqli->query($grab3);
$result4 = $mysqli->query($grab4);
$result5 = $mysqli->query($grab5);
$result6 = $mysqli->query($grab6);
// Convert result into an array called items
$item1 = mysqli_fetch_row($result1);
$item2 = mysqli_fetch_row($result2);
$item3 = mysqli_fetch_row($result3);
$item4 = mysqli_fetch_row($result4);
$item5 = mysqli_fetch_row($result5);
$item6 = mysqli_fetch_row($result6);
I managed to solve this with help on this thread..
I replaced all this code with:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value) {
$grab[$key] = "select * from stock_tbl where stock_id='$value'";
$result = $mysqli->query($grab[$key]);
$item[$key] = mysqli_fetch_row($result);
}
Thank you very much :)
First of all, do you really need *?
What's wrong with using a single query with the IN() function? For example:
// Create 6 random numbers from table
$ran_num = (RandomInRange(1,$total,6));
// Select(grab) data from table from a random row
$grab = 'SELECT * FROM stock_tbl WHERE stock_id IN ('.implode(',', $ran_num).')';
<?php
$ran_num = (RandomInRange(1,$total,6));
foreach ($ran_num as $key => $value)
{
$grab[$value] = "select * from stock_tbl where stock_id='$value'";
}
?>
If you don't need to access each statement individually, this is also possible:
<?php
$ran_num = (RandomInRange(1,$total,6));
$grab = '';
foreach ($ran_num as $key => $value)
{
$grab .= "select * from stock_tbl where stock_id='$value';";
}
?>
That's essentially creating one long string that SQL will parse as individual commands using the semi-colon as the delimiter for each one.
You can concatenate strings in PHP with the '.' operator. Also, setting the grab variables as an array will make this easier as well, if that is possible in your implementation. You're probably looking for code such as:
for (int i=0; i < 20; i++)
$grab[i] = "select * from stock_tbl where stock_id='$ran_num[".i."]'";
Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";
Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);