I'm working on a page, where users post their betting picks. In MySQL I have the table bets (id, event, pick, odds, stake, analysis, status, profit).
I would like to check if 'status' is empty in MySQL, but the if() statement is not working. If it's empty, it should output all the bets from a user. The code posted is in a for loop.
So what is wrong with the if() statement? And is there any better way to do this?
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
$row = mysqli_fetch_array($result);
if ('' !== $row['status']) {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
You are using identical comparison, which would check for type & value both. === or !== as this involves comparing the type as well as the value.
Instead try -
if (!empty($row['status'])) { // assuming status would hold only strings (not false/0 etc)
Or
if ($row['status'] != '') {
Use mysqli_num_rows(). If its greater then 0 then we can say that query containing result so we can further proceed.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
if ($row['status'] != "") {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
}
For status check you can use any of below method
if ($row['status'] != "") { }
OR
if (!empty($row['status'])) { }
If it's empty, it should output all the bets from a user. The code posted is in a for loop.
Since you are checking if it's empty, your if statement should be the other way round:
if ($row['status'] == '') {
Alternatively, you can use mysqli_num_rows() get the number of rows:
Returns the number of rows in the result set.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
Also, there isn't such function called queryMysql():
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
It should be mysqli_query(). For mysqli_query(), the connection parameter is needed.
$result = mysqli_query($conn, "SELECT * FROM bets WHERE user='$user'");
Related
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
I have a webpage which sends a query to my MySQL database to retrieve information about my company's suppliers and echos the results (all fine so far). It then makes a second query to check if there are any known contacts associated with that supplier:
while ($row = mysqli_fetch_array($result)) {
$contact = $row["contact"];
echo $row["name"] . "<br>" . $row["category"] . "<br>" . "Telephone: " .
$row["telephone"] . "<br>" . "Fax: " . $row["fax"] . "<br>" .
$row["email"] . "<br>" . $row["address"] . "<br>" .
$row["postcode"] . "<br><br>" . "Contact: " .
$contact . "<br>";
$resultContact = mysqli_query($con,"SELECT * FROM contacts WHERE name =
'$contact'");
while($rowContact = mysqli_fetch_array($resultContact)) {
echo $rowContact["telephone"] . "<br>" . $rowContact["email"];
echo "<br>";
}
}
($row is from the first query and works.) However, echo $rowContact["telephone"] . "<br>" . $rowContact["email"]; just prints whitespace.
Thanks
EDIT: if I use a string literal in the Where clause, it works as it should. However, I used variables in exactly the same way as I am now in the first query and that works! I am confused :(
EDIT 2: the first query: $result = mysqli_query($con,"SELECT * FROM suppliers WHERE LOWER(name) = LOWER('$searchText')");
EDIT 3: the result of doing var_dump($resultContact);: object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(4) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) } I'm guessing this means that the query is coming back with the table ok, but the Where clause isn't comparing the contact name as I want it to...
Your query must be mysql_query, not mysqli_query.
This is the correct code:
//Your db connection
mysql_connect('localhost','root','');
mysql_select_db('database');
//queries and data
$result = mysql_query("SELECT * FROM suppliers WHERE LOWER(name) = LOWER('$searchText')");
while ($row = mysql_fetch_array($result)) {
$contact = $row["contact"];
echo $row["name"] . "<br>" . $row["category"] . "<br>" . "Telephone: " .
$row["telephone"] . "<br>" . "Fax: " . $row["fax"] . "<br>" .
$row["email"] . "<br>" . $row["address"] . "<br>" .
$row["postcode"] . "<br><br>" . "Contact: " .
$contact . "<br>";
$resultContact = mysql_query("SELECT * FROM contacts WHERE name =
'$contact'");
while($rowContact = mysql_fetch_array($resultContact)) {
echo $rowContact["telephone"] . "<br>" . $rowContact["email"];
echo "<br>";
}
}
On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist.
Here's my code:
if ($Type == 1)
{
$mysqli = new mysqli("localhost","----","----", "----");
if (!$mysqli)
$Type = 3;
$Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_Out'];
if ($Row2 !== "-1") $Type = 4;
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
$Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row2 = $Row['Time_In'];
$Time2 = explode(":",$Row2);
$Hour2 = $Hour - $Time2[0];
if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"))
{$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'");
$Row = $Select->fetch_assoc();
$Row3 = $Row['Hours'];
$Auto += 1;}
$Time3 = 60-$Time2[1];
if ($Hour != 21) $Time4 = $Min;
$Time5 = $Time3+$Time4;
if ($Time2[0]+1 != $Hour)
{$Time5 = $Time5+60;}
$Total = $Time5+intval($Row3);
if ($Type == 1)
{
if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'"))
{$Auto += 1;}
else
{$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");}
}
$mysqli->close();
}
if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!";
if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!";
if ($Type == 3) echo "An unexpected error has occured. Please try again!";
if ($Type == 4) echo "You have already signed out today!" . $Auto;
if ($Type == 5) echo "You didn't sign in today.";
The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows).
Change this:
if ($Type == 1)
{if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"))
{}
else
{$Type = 5;}
}
To this:
if ($Type == 1) {
if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0)
$mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'");
else
$Type = 5;
}
You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.
What is resource(150) of type (mysql result)? I am getting that after var_dumping an select query,
My code is:
$userlevelcheck = $this->query_silent("SELECT user_level FROM " . DB_PREFIX . "users WHERE user_id='" . $user_id . "'");
var_dump ($userlevelcheck);
if ($userlevelcheck != "1")
{
code
}
Try:
$userlevelquery = $this->query_silent("SELECT user_level FROM " . DB_PREFIX . "users WHERE user_id='" . $user_id . "'");
$row = mysql_fetch_assoc($query);
if ($row['user_level'] != "1")
{
code
}
You need to get the row with the data in ($row) then check the relevant field $row['user_level']
PHP sessions work by default with my configuration, if I just go session_start() and try the standard session increment test it works.
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
However I want to use a MySQL table for session storage. I've put together my sessions.php file with all the functions, copied them right out of a book like a n00b, and the functions work (affect the database) if I call them like regular functions, but using the standard test above does not work. It sets the session for just the page load, and no change in the database. I put a line in each function to log each call, and the log reflects that the functions are being called by session_start().
Here's what my code looks like:
session_module_name("user");
session_set_save_handler("session_open", "session_close",
"session_read", "session_write", "session_remove", "session_gc");
session_start();
session_open, etc, being the name of my functions. I've even tried another set of functions out of an o'rly example, and got the same results.
Any ideas why? session_register() also yields the same results.
EDIT: here are the actual functions, I apologize for the length, but I log everything in dev.
function session_db(){
return("my_db_name");
}
function session_table(){
return("sessions_table");
}
function session_log($message){
if($file = fopen($application["siteroot"] . 'log/session.txt', "a")){
fwrite($file, date("Y-m-d H:i:s ") . $message . "\n");
fclose($file);
}
}
function session_open($path, $name){
session_log("session_open");
return(true);
}
function session_close(){
session_log("session_close");
return(true);
}
function session_read($id){
session_log("session_read");
if(!mysql_select_db(session_db())){
session_log("session_read select database error: " . mysql_error());
return(false);
}
$sql = "select * from " . session_table() . " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("MySQL error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_num_rows($result)){
session_log("MySQL query returned " . mysql_num_rows($result) . "rows.");
$row = mysql_fetch_assoc($result);
session_log("session_read returned " . $row["data"]);
return($row["data"]);
}
else{
session_log("session_read found zero rows with SQL: " . $sql);
return("");
}
}
function session_write($id, $data){
session_log("session_write");
if(!mysql_select_db(session_db())){
session_log("session_write select database error: " . mysql_error());
return(false);
}
$sql = "update " . session_table() . " set data = '" . addslashes($data) . "', time=null";
if(isset($PHP_AUTH_USER)){
$sql .= ", user='" . addslashes($PHP_AUTH_USER) . "'";
}
$sql .= " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_affected_rows()){
session_log("session_write update affected " . mysql_affected_rows() . " rows with SQL: " . $sql);
return(true);
}
session_log("session_write updated zero rows with SQL: " .$sql);
$sql = "insert into " . session_table() . "(data,id) values('" . addslashes($data) . "','" . $id . "')";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . "with SQL: " . $sql);
return(false);
}
else{
session_log("mysql_write inserted with SQL: " . $sql);
return(true);
}
}
function session_remove($id){
session_log("session_remove");
if(!mysql_select_db(session_db())){
session_log("session_remove select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where id='" . $id . "'";
if($result = mysql_query($sql)){
session_log("MySQL query delete worked");
return(true);
}
else{
session_log("MySQL update error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
function session_gc($life){
session_log("session_gc");
if(!mysql_select_db(session_db())){
session_log("session_gc select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where time < '" . date("YmdHis", time() - $life) . "'";
print("session_gc sql: " . $sql);
if($result = mysql_query($sql)){
session_log("session_gc deleted " . mysql_affected_rows() . " rows.");
return(true);
}
else{
session_log("session_gc error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
I don't think you need the call to session_module_name, try commenting it out and see what happens.
There are a couple of things...
We might need to see, at the very least, the actual functions.
You probably want to register a shutdown function, your writes are probably being called too late to save to the database.
register_shutdown_function('session_write_close');
Just to clarify, the reason for the above is that the write and close functions are normally called after objects are destroyed. This call will ensure that these are made before object destruction.