im new student of php and mysql. I'm doing a voluntary little game for class. But I can not understand why when doing mysqli query it returns an int 0 when the database has 500 assigned. The game consists of a user who bets a certain amount of coins of his account, then a dice decides whether you win or not, taking 1,2,3 you lose, 4,5,6 you win. I post here the error or whatever this is.
include('conexion.php');
include('session.php');
$usuario=$_SESSION["username"];
$apuesta =$_POST["apuesta"];
$coins= "SELECT coins FROM `users` WHERE `usuario` = \"$usuario\"";
if (mysqli_query($conn, $coins)){
echo "<br>";
echo "hola";
echo "<br>";
var_dump($coins);
echo "<br>";
$coins2 = (int)$coins;
var_dump($coins2);
echo "<br>";
echo "<br>";
var_dump($coins2);
echo "<br>";
if ($apuesta>=$coins2) {
echo "No tienes suficiente saldo";
echo "<br>";
}else {
$dado = rand(1,6);
if ($dado >3) {
$apuesta = $coins2 + $apuesta;
$cambiocartera = "UPDATE `users` SET `coins` = $apuesta WHERE `users`.`usuario` = '$usuario'";
echo "<br>";
echo "<h1>Ganaste = $dado";
header( "refresh:3;url=dashboard.php");
}
elseif ($dado<4) {
$apuesta = $coins2-$apuesta;
$cambiocartera = "UPDATE `users` SET `coins` = $apuesta WHERE `users`.`usuario` = '$usuario'";
echo "<br>";
echo "<h1>Perdiste = $dado</h1>";
header( "refresh:3;url=dashboard.php" );
}
}
}else {
echo"error";
}
My browser message about the int on 0 that i dont understand why.
$coins is the string containing the query, it's not the column you're retrieving from the table. When you convert a string to a number, it returns 0 if there's nothing numeric at the beginning.
You need to assign the result of mysqli_query() to a variable, then call a fetch function on that.
if ($result = mysqli_query($conn, $coins)) {
$row = mysqli_fetch_assoc($result);
$num_coins = $row['coins'];
var_dump($num_coins);
Related
I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.
I'm learning PHP and getting a little frustrated. I have an html form that is sending data to another php page $_POST["id"];.
On a 2nd php page I'm trying have the "available" column in the table either switch to 1 or 0. If it's already 1 go to 0, and if it's 0 go to 1.
I know my code is probably completely wrong and messy but please excuse me as I'm still learning.
if ($row["available"] == 1) {
//$row["available"] = 0;
$sql = "UPDATE check_in_out SET available=0 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
} else {
//$row["available"] = 1;
$sql = "UPDATE check_in_out SET available=1 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
If you want to toggle the value you can use this:
$sql = "UPDATE check_in_out SET available = (1-available) WHERE id='".$_POST["id"]."'";
or
$sql = "UPDATE check_in_out SET available = IF(available = 0, 1, 0) WHERE id='".$_POST["id"]."'";
I am using the following code to determine if a user is signed in or not, I have set the field 'first_sign_in' to 0 in the mysql table but I am still receiving the echo 'already signed in for the start of the day when actually it should return 'not signed in for the start of the day'
Could someone help me on where I am going wrong here.
$time = date('h:i:s', time());
$checkifstaffexists = mysql_query("SELECT user_id from staff WHERE pin = 3012");
if (!$checkifstaffexists) {
die('Failed.');
}
if (mysql_num_rows($checkifstaffexists) > 0) {
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
if ($checkfirstsignin == 0) {
echo 'not signed in for start of day</br>';
$checksignintime = mysql_query("SELECT " . date("d") . " " . "_start from staff WHERE pin = 3012");
if($checksignintime > $time) {
echo 'user is late';
$addtolatetable = mysql_query("INSERT INTO lates (user_id, date_time) SELECT user_id, '2014-05-15 12:00:00' from staff WHERE pin = 3012");
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is not late';
//$signuserin = mysql_query(" ")
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
}
} else {
echo 'already signed in for start of day</br>';
$checkifuserisinourout = mysql_query("SELECT status from staff WHERE pin = 3012");
if ($checkifuserisinourout == 0) {
echo 'user is not signed in so we will sign you in';
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is signed in so we will sign you out';
//$signuserout = mysql_query(" ");
$changestatustoout = mysql_query("UPDATE `staff` SET status=0 WHERE pin = '3012'");
//redirect
}
}
} else {
//The user cannot be found
echo 'User doesn\'t exist.';
}
with the line
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
you get back a resource that you have to use to fetch data, for example:
$row = mysql_fetch_assoc($checkfirstsignin);
and with this array ($row) you can work further.
Please check the manpage for mysql_query for further reading...
and since this will be posted all the time: mysql_* methods are deprecated, please use mysqli or pdo.
if ($checkfirstsignin == 0)
Will always equal true if the query succeeds even if there are no matching results.
You need to use mysql_fetch_row or mysql_fetch_array to do that.
while($row = mysql_fetch_assoc($checkfirstsignin)){
if($row['first_sign_in']==0){
//do something
}
}
Write this var_dump( $checkfirstsignin );
after this line $checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
And you will see the returned result is an array, so it is always false on the next if check.
Im trying to make a code where it displays all names in database where "clanwars" is set to 1 (int) and if all of them is 0 echo an message like: "Noone has signed up yet!"
This is some of the code i have:
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
while($row = mysqli_fetch_array($result))
{
if ($row['clanwars'] != '0') {
echo $row['mantra']."<br>";
} else {
echo 'Noone has signed up yet!';
}
}
mysqli_close($con);
First, in your example row['clanwars'] will never equal to 0 because you already specified WHERE clanwars = 1 in your query, so MySQL will return only those that have clanwars=1. If I understand well, you need to do something like:
<?
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
if (mysqli_num_rows($result)==0) echo 'Noone has signed up yet';
else {
while ($row = mysqli_fetch_array($result)) {
//do what you need
}
}
?>
So basically, you retrieve everyone who has CLANWARS set to 1 in the database. If there are records, process them, if there are no records, it means that nobody has signed up.
Is this what you need?
Try this:
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
if (mysqli_num_rows($result) == 0)
{
echo 'Noone has signed up yet!';
}
else
{
while ($row = mysqli_fetch_array($result))
{
echo $row['mantra']."<br>";
}
}
mysqli_close($con);
Code:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table`
WHERE `Username` = '$Username'
ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) { ?>
<?php if(!isset($db['article'] && $db['subject'])) {
echo "Your articles";
} else {
echo "You have no articles added!";
} ?>
<?php } ?>
So I want the rows for example(db['article'] and $db['subject']) from a specific username (see: $Username = $_SESSION['VALID_USER_ID'];) to echo the information if is not empty else if is empty to echo for example "You have no articles added!"
If is some information in the rows the code works, echo the information BUT if the rows is empty don't echo nothing, the code should echo "You have no articles added!" but this line don't appear, where is the mistake?
I tried for if !isset, !empty, !is_null but don't work.
I think what you're trying to achieve is:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
if(mysql_num_rows($q) > 0)
{
echo "Your articles:\n";
while($db = mysql_fetch_array($q)) {
echo $db['subject']." ".$db['article']."\n";
}
}
else
{
echo "You have no articles added!";
}
?>
I don't understand. Do you have article rows with username, but without article, i.e.:
| id | user | article |
-------------------------------------
| 1 | X | NULL |
If so, you can test with:
if($db['article'] == NULL) { .... } else { .... }
Otherwise, if you don't have a row with user=x, when there are no record, mysql will return an empty result.
So, basicly, if no rows are found on selection: SELECT * FROM article_table WHERE Username = 'X';, you can test
if(mysql_num_rows($q) > 0) { .... } else { .... }
However, mysql_ functions are not recommended anymore. Look at prepared statements.
You have a logic error in your if statement -- what you want is to check if both the article and subject are set.
With your current code, you compare $db['article'] with $db['subject'], and check if the result is set. You need to change it a bit :
Instead of :
if(!isset($db['article'] && $db['subject'])) {
Try:
if(isset($db['article']) && isset($db['subject'])) ...
I would do something like this:
$articles='';
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
if(isset($db['article']) && isset($db['subject'])) {
$articles .= $db['article']."<br/>";
}
}
if($articles != ''){
echo $articles;
}
else{
echo "No articles";
}
?>
fastest way to achieve what you want is by adding a variable that will verify if the query returned any rows:
<?php $Username = $_SESSION['VALID_USER_ID'];
$i = 0;
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
$i = 1;
if(!isset($db['article'] && $db['subject'])) { echo "Your articles"; } ?>
<?php }
if ($i == 0) echo "You have no articles";
?>
You tried to echo "no articles" in the while loop, you get there only if the query returns information, that is why if it returns 1 or more rows, $i will become 1 else it will remain 0.
In your case:
$numArticles = mysql_num_rows($q);
if($numArticles > 0)
echo 'Your articles';
else
echo 'No articles :((((';
I recommend tough moving on to PDO to communicate with DB.