I want to have a row with a column called: 'seen', then this column will have either a default of no value or a 'yes' value.
So..
Grab one row where it hasn't been 'seen' before.
Update the above row 'seen column' to say 'yes'.
If all rows have the value of 'yes' then a notice/error displays:
You have successfully completed all numbers.
I've tried the best I can do achieve it, but it's not working. I think my logic in tackling this may be incorrect?
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Grabs one row where it hasn't been seen before
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE seen='' ORDER by rand() LIMIT 1");
// Updates the above row with the 'seen' column saying 'yes''
$query = mysqli_query("UPDATE num_image SET seen = yes");
// Fetches Result
$thestuff = mysqli_fetch_row($query);
$seenme=$_POST['seen']; // get value of 'seen' column
$result = mysqli_query("SELECT * FROM num_image where seen=$seenme");
// Trying to delivery a message if the enitre 'seen' column is ALL yes.
while($row = mysqli_fetch_row($result))
{
if($row['seen'] == 'yes')
{ // All numbers seen
echo 'You have successfully completed all numbers.';
echo json_encode($thestuff);
}
else
{ // Show numbers
echo json_encode($thestuff);
}
}
Does the SELECT and UPDATE row also have to be an if statement?
Cheers
You have to escape the value in the Update sentence:
$query = mysqli_query("UPDATE num_image SET seen = 'yes' ");
Related
I have one drop down and lists are aMan, bMan, cMan.I am selecting any one of them from drop down. So whatever I am selecting from drop down I want to update that records according to list. Below update query is updating all my records because i added '$action_points' for each.
For example. If I selected bMan from the drop down then in update table will update only bMan records according to user_id.If I select aMan then update table it will update only aMan with 10.It will not effect on other.
I am getting the issue on update query.Would you help me with update query?
$result = $conn->query($sql_user);
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
}
}
$sql = "UPDATE man SET aMan='$action_points',bMan='$action_points', cMan='$action_points' where user_id='$user_id'";
$result = $conn->query($sql);
Update table
You are selecting from select drop down it means it will pass the value, that you have either aMan, bMan or cMan.
so you can do it like this,
$action_type = $_GET['action_type'];
$sql = "update man set `$action_type` = '$action_value' where id = $user_id";
Above is an example.
Firstly, you should replace if (isset($result -> num_rows) >0 ) with if(isset($result)) && ($result->num_rows>0)) .The first condition returns the number of rows (which at the least is 0) and then checks if it is set. Thus, isset will always return true, even when $result is not set. The second condition solves this problem
You have the type of list to update, why don't you use it?
For eg:
$result = $conn->query($sql_user);
if(isset($result)) && ($result->num_rows>0)) {
// output data of each row
while($row = $result->fetch_assoc()) {
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
}
}
$sql = "UPDATE man SET $action_type = $action_points WHERE user_id='$user_id'";
$result = $conn->query($sql);
This shall automatically update the required column
U should use AND in your query
UPDATE man SET aMan='$action_points' AND bMan='$action_points' AND cMan='$action_points' where user_id='$user_id'"
Or use several update query it means once update aMan row then a query for bMan row and so on.
The issue is because you are updating the three column at a time, you have to make it conditional like:
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
$column = '';
if($action_type == 'aMan'){
$column = 'aMan';
}
else if($action_type == 'bMan'){
$column = 'bMan';
}
else if($action_type == 'cMan'){
$column = 'cMan';
}
$sql = "UPDATE man SET ".$column." = '".$action_points."' where user_id='$user_id'";
I am trying to get the last value of a field during a new registration.
before insert data into the table, I want to create a user id number according to the last registered user's id number. to do that I use this:
//to reach the last value of userID field;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$value = $row['userID'];
echo "$value"; //not resulting here
}
$userID = $value+1;
so, the userID becomes 1.
The weird thing is, I could capable to use exact same code in another php file and works fine.
I would like to say that, rest of the code works fine. No problem with db connections or any other things you can tell me.
Note that: When I run the same query line in the mysql interface, I can get the value I want. I mean $sql line.
Your problem is in this code:
{
$svalue = $row['userID'];
----^
echo "$value"; //not resulting here
}
$userID = $value+1;
Change to $value.
But the right answer is to define userID to be auto-incrementing. That way, the database does the work for you. After inserting the row, you can do:
SELECT LAST_INSERT_ID()
To get the last value.
I solved the problem. Here;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
$user_info = $result->fetch_assoc();
$value = intval($user_info["userID"]);
$userID = $value+1;
Thanks everyone.
If you mark the userID field as autoincrement in you mysql table.
You won't need to set the userID and db increase the userID for you. You can get the assigned userID using the mysql_insert_id() function. Here is an example from php.net
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Here is another example for your case
mysql_query("INSERT INTO 'loto_users'('username',...) values('usernameValue',...)");
echo "New User id is ".mysql_insert_id();
I Have the following code:
<?php
error_reporting(E_ALL);
// connect to your MySQL database here
$dbhandle = mysql_connect('xxx', 'xxxx', 'xxxx');
$selected = mysql_select_db("xxxx",$dbhandle);
// Get the winner data
function setWinner(){
$sql = 'UPDATE user SET winner = 1 WHERE id=(SELECT id FROM user ORDER BY RAND())';
$query = mysql_query($sql) or die (mysql_error());
echo $query;
}
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user WHERE winner = 1';
$query = mysql_query($sql) or die (mysql_error());
if(mysql_num_rows($query) == 1) {
$user = mysql_fetch_assoc($query);
} else {
// If there is no winner yet, automatically create one
setWinner();
// Recall the function which should now find a winner
$user = getWinner();
}
return $user;
}
$winner = getWinner();
print_r($winner);
?>
Trying to work with g4vroche's answer but getting this error: You can't specify target table 'user' for update in FROM clause
I used this for a competition to select a random user from the database, but i now need it to look through all the users to see if there's a user that's winner column equals 1 and if there isn't one it should select the random user and update that users winner column with 1.
Any Help greatly appreciated.
I'm using the mysql_query() function just because you used it in your example. You should read up on PDO and implement that instead.
Per my comment above,
require_once "connect_to_mysql.php";
// look for records with `winner` set to 1
$result = mysql_query('SELECT id, fullname, email, number FROM user WHERE winner = 1 LIMIT 1') or die (mysql_error());
if (mysql_num_rows($result) < 1) { // if no records were found, pick a random row
$result = mysql_query('SELECT id, fullname, email, number FROM user ORDER BY RAND() LIMIT 1');
}
I don't know what your winner column actually stores, but assuming it's a boolean, which may contains only 0 or 1, you could do this in a single query :
SELECT id, fullname, email, number FROM user ORDER BY winner DESC, RAND() LIMIT 1;
Which will :
Sort all records on winner column, making rows hanving winner = 1 firsts
Sort equals records with RAND()
So you will get and random result, priority being given to records having winner column equals to "1".
EDIT
I missunderstood your need.
You have two different process here
Get the winner
Set the winner
You should probably split that into two function / methods
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user winner=1';
$query = mysql_query($sql);
mysql_num_rows($result) == 1) {
$user = mysql_fetc_assoc($query);
return $user;
}
return false;
}
function setWinner()
{
$sql = 'UPDATE user SET winner=1 ORDER BY RAND() LIMIT 1';
mysql_query($sql);
}
// Call this one time
setWiner();
// Call this any time you want to get the winner's data
$winner = getWinner();
A more lazy approach, will be to make the getWinner() function to call setwinner if there is no winner yet :
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user winner=1';
$query = mysql_query($sql);
mysql_num_rows($result) == 1) {
$user = mysql_fetc_assoc($query);
} else {
// If there is no winner yet, automatically create one
setWinner();
// Recall the function which should now find a winner
$user = getWinner();
}
return $user;
}
That's up to your context, but on general point of view it's bad practice, because a function which looks like reading data (getSomething) will, under some circumstances, also alter data (call to setWinner().
I want to update some entries in my database, basically I am counting the number of checkboxes that have been selected on the previous page and multiplying them with 25 then adding that value to the current value in the DB.
This is my code:
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>
It seems, that for some reason it is multiplying $countx25 with the number of checkboxes before inserting it into MySQL. This if($result){echo "$countx25";}} always shows me the right value though.
If i select 1 it prints 25, 2 prints 50, 3 prints 75 and so on, but for the MySQL part, if i select 1 it adds 25 to current value, 2 adds 100, 3 adds 225 ?!
What's the error here ?
In your SQL query:
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
You don't tell the database which row to update, so all rows are updated. While you test, you first test once, then again and again, so it might add to fields you don't expect it to. Probably this is your problem.
To specify which row to update, use a WHERE clauseDocs.
To prevent updating the same field more than once, execute the query only once.
As I stated in my comment. You are running this for each checkbox you get via $_POST. Why do you even use the for loop if you use count to count the checkboxes. Remove the for loop and it will work as you intend it to.
The for loop in your code is the problem. I guess here you are trying to use all checkboxes in the previous page, for your code you loop for all the checkboxes, so if there are 4 checkboxes, the for loop will run 4 times. So please identify what you want to do.
This is your code.
<?php
if($_POST['code_approve'])
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$approval_id = $checkbox[$i];
$checkboxCount = count($_POST['checkbox']);
$countx25 = $checkboxCount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = balance+'$countx25'";
$result2 = mysql_query($sql2);
$result = mysql_query($sql);
}
if($result)
{
echo "$countx25";
}
}
?>
say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert