Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm in the process of implementing a system that keeps track of all instances when a product goes in and out of stock. I have a column in the table that keeps track of whether or not a given record is open or closed (open meaning it's out of stock and hasn't been restocked and closed meaning it came back into stock at some point). Up to this point, I haven't had that many issues with SQL queries when it came to making sure they worked. However, I've been running the script used for this table population and nothing is being inserted into the table.
The functions I use for this specific table's updates are as follows.
//Records item as being back in stock
function itemInStock($item){
$db_controller = new DBHandler();
$selectQuery = "SELECT * FROM out_of_stock_record
WHERE ListID = '$item->ID'
AND Status = 'OPEN'";
$rs = $db_controller->select($selectQuery);
/*If this record exists, then the only thing we need to do is update the BackInStockTS and Status columns. It came back in stock on this date at this time, therefore it's closed.*/
if($rs){
$currentDate = date("Y-m-d H:i:s");
$updateQuery = "UPDATE out_of_stock_record
SET BackInStockTS = '$currentDate', Status = 'CLOSED'
WHERE ID = '$item->ListID' AND Status = 'OPEN'";
$db_controller->update($updateQuery);
}
}
//Records item as being out of stock
function itemOOStock($item){
$db_controller = new DBHandler();
$selectQuery = "SELECT ID FROM out_of_stock_record
WHERE ID = '$item->ID'
AND Status = 'OPEN'";
$rs = $db_controller->select($selectQuery);
/*We only need to make sure the record DOESN'T exist, because if that's true, then all we need to do is insert this. If it already exists, there's nothing to do.
The only other check occurs later on that sees if the item is back in stock, then updates the existing open record in order to close it and record the date it
came back in stock.*/
if(!$rs){
$currentDate = date("Y-m-d H:i:s");
$start = "INSERT INTO out_of_stock_record (ID, OutOfStockTS, BackInStockTS, Status) VALUES (";
$end = sprintf("'%s', '%s', NULL, '%s')", $item->ID, $currentDate, "OPEN");
$start .= $end;
$db_controller->insert($start);
}
}
I don't know what the issue is. I use the exact same database handler for insertion on a differently-named table in another part of this script that I have zero issues with, and I'm not sure it has something to do with the table's structure. It consists of varchar columns for both ID and status, datetime columns for the OOS and IS dates, and I included another column for recording the last update for this table, but that just changes automatically when insertion occurs.
I haven't had any issues with this script before aside from some that I unintentionally created and later corrected. The table is supposed to update every time I visit the URL for this page. Any suggestions on what may be causing this? If it helps, the database this script uses and the site that it's hosted on are on the same server.
I was using the wrong check for the if statements. They should have looked like these.
if(mysql_num_rows($rs) == 0){
//Insert record
}
if(mysql_num_rows($rs) != 0){
//Update record
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to create an autofill info button that retrieves the last inserted information from MySQL and coupled with a $_GET autofills the page with the latest update. I am able to insert and update the data base just fine however upon retrieval of the information my variables remain empty.
I have verified the project-fill button is being posted. I also didnt get any error when checking the query's.
below is a snippet of the section that isnt working. It prints my header but the variables remain empty.
Apologies for sloppy code pretty green.
if(isset($_POST['project-fill'])) {
require "dbh.inc.php";
//select the last inserted row the one with the highest id
$proj1 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
$proj2 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
$proj3 = mysqli_query($conn, "SELECT * FROM updates WHERE id = MAX");
//select the column out of that row
$result1 = mysqli_fetch_row($proj1['Project1']);
$result2 = mysqli_fetch_row($proj2['Project2']);
$result3 = mysqli_fetch_row($proj3['Project3']);
//transfer to project variable
$project1 = $result1;
$project2 = $result2;
$project3 = $result3;
//print header to allow for the $_GET method on the project page
header (Location: ../update.php?update=sucessful&p1=".$project1."&p2=".$project2."&p3="$.project3);
}
This is not the correct way to fetch a row from a result:
$result1 = mysqli_fetch_row($proj1['Project1']);
$proj1 is a mysqli_result object, not an array, so you can't subscript it. You need to pass the object to mysqli_fetch_assoc(), and it returns an associative array with an element for each column.
$proj = mysqli_query($conn, "
SELECT Project1, Project2, Project3
FROM updates
ORDER BY id DESC
LIMIT 1");
$row = mysqli_fetch_assoc($proj);
$project1 = $row['Project1'];
$project2 = $row['Project2'];
$project3 = $row['Project3'];
You don't need to query 3 times to fetch different columns from the same row.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I try to do it it fetches the entire column, not just one field.
$connection = mysqli_query($db, "SELECT * FROM users");
<?php
while($row = mysqli_fetch_array($connection)) {
?>
<p>Your balance is: <?php echo $row['balance']; ?></p>
<?php
}
?>
That was outputting
Your balance is: 5
Your balance is: 0
Your balance is:
So I tried
$query_for_selecting = mysqli_query($db, "SELECT balance FROM users");
<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php } ?>
And that wasn't outputting anything so eventually, I tried using a WHERE clause and a limit of 1
$query_for_selecting = mysqli_query($db, "SELECT * FROM users WHERE balance = '3' DESC LIMIT 1");
<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php } ?>
All I got was a white screen
I think a basic little tutorial might be in order here.
First off: SELECT * FROM users means: "give me everything in the users table". You will get the full table, every row and every column.
while($row = mysqli_fetch_array($connection)) will loop through every row your query returns. It will call mysqli_fetch_array() and put the result in $row until there are no more rows in your query's result.
If you only want to output a single row of data, you have three options:
Add a WHERE condition so that your query will only fetch a specific row
Add a LIMIT clause so that your query will only fetch a single row
Call mysqli_fetch_array() only once instead of in a while loop
From the comments in the discussion thread, it looks like you want to retrieve only the balance for the currently logged in user, and you have a session variable somewhere that tells you who that user is. That means you'll want to use a WHERE condition so that your query will only fetch the row for that specific user.
You haven't told us what that session variables is called or what the name is of the column in the users table that you can compare that session variable with, so I'll assume that your users table has an id column and your session variable is called user_id and should match the id value from your users table.
So let's say the user with id 123 is currently logged in. You'll want to end up with the query SELECT balance FROM users WHERE id = 123.
The quick solution is to change your code to:
$connection = mysqli_query($db, "SELECT balance FROM users WHERE id = " . $_SESSION['user_id']);.
This is bad code. We'll make it better, but try this first and see if it gets you the result you actually want. If it doesn't, let me know.
The reason this is bad code is because adding variables to a query string like this dramatically increases the risk of SQL injections. If there's any possibility at all that the value of the variable comes from user input, then at some point a user will figure that out and make sure it contains something that will break your application.
Best case scenario: the page simply won't render for that one user.
Bad case scenario: the user will be able to read out your entire database and will sell sensitive user data to the highest bidder.
Worst case scenario: the user will be able to inject some of their own Javascript code into your database in a column you're not sanitizing before rendering, letting them capture and intercept passwords and/or financial information your users are entering on your site and they will then use that information to make life miserable for all of your users.
So you don't want to just drop $_SESSION['user_id'] into your query like that. Instead, you'll want to use a prepared statement and let the database handle the problem of dropping the variable into the query.
First, you'll need to prepare your query:
$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");
The ? symbol is a placeholder where you can bind a parameter. Let's do that:
$statement->bind_param("i", $_SESSION['user_id']);
The "i" tells MySQL that you're binding an integer value. If you're not matching against a user id but a username, for example, you'll want to instead use "s" to tell MySQL you're binding a string value.
Now you can execute the query and get the result. Putting it all together:
$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");
$statement->bind_param("i", $_SESSION['user_id']);
$statement->execute();
$connection = $statement->get_result();
Let us know if that works. Some tweaking might be required.
I have a feeling as to what's going on. You're fetching the entire database without either using a LIMIT of 1 and/or use a WHERE clause, given that you have unique ID's somewhere for columns. I am sure that you have more than the one record in your database table.
I was going to post this in a comment but decided not to. Stack doesn't really want us to do that, (edit) and at this point, it is way too long for a comment.
#ADyson "I initially wanted to display the balance of the user that's logged in, but that didn't work out." – markthedark
About that. It seems that what you are looking for is to get the balance for a user/record in particular. For that, you definitely need to use a WHERE clause.
If your query failed, enable error reporting and checking for errors on the query.
References:
https://www.php.net/manual/en/function.error-reporting.php
https://www.php.net/manual/en/mysqli.error.php
Plus, the $i = 0; and $i++; may not be helping. It's hard to say what that is supposed to do. I know the syntax, I just don't know why you're wanting to increase it.
Side note: I would avoid in using $connection as a query variable assignment. It could be confusing. Try to use something clear like $query_for_selecting.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a little problem, am trying to read values from mysql table. I have done research and could not find a definite or conclusive answer on this. I will describe the problem:
select data from mysql table using a where e.g where gender=female.
count the results and return the count - just to help know how many records were found
compare a value in table, e.g 'taken' and 'available',
if 'taken' = 'available' in the first record, go to next record(and compare again), if not perform a specific operation in this case can be update or insert or anything of that sort.
the first three are ok and the only problem is, part 4. Kindly help. This is a php problem. Looking forward for your help.
As was said, if you're merely going to skip the record then you may as well not retrieve them in the first place (and thus incur the overhead for having to extract them into PHP memory, etc):
SELECT * FROM `your_table` WHERE `gender` = 'female' AND `taken` = `available`;
However, if you have a specific reason to do this, you can merely do the following:
foreach ($hotels as $hotel) {
// skip if the item is not available, logic can be changed if necessary
if ($hotel->taken >= $hotel->available) continue;
// do the other work here...
}
I interpreted your conditions a little here, assuming you wanted to skip people who aren't 'available'. Though it does look like you wanted the opposite, in which case you can switch the logic in the sql from != to = and in php from != to ==.
Updated: To reflect additional comments made.
Create connection to your database using mysqli or by using PDO.
$db = new PDO($mysqlhost,$username,$password);
$statement = $db->prepare($sqlstatement);
$rows = $statement->execute();
foreach($rows->fetch() as $row)
{
if($row['column_name']==something)
{
//do work
}
else
{
//do work
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am a beginner in PHP and SQL. I have been trying to delete rows in SQL table using the following code but it doesn't work. Please help.
<?php
/*
DELETE.PHP
Deletes a specific entry from the 'db' table
*/
// connect to the database
include('connect-db.php');
// check if the 'id' variable is set in URL, and check that it is valid
// get id value
$id = $_GET['id'];
// delete the entry
$result = mysql_query("DELETE FROM db WHERE 'Report No.'= '$id'")
or die(mysql_error());
// redirect back to the view page
header("Location: view.php");
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: view.php");
}
?>
Apply backticks(`) around table field name "Report No." (its not standard way to define a table field name)
Try this
$result = mysql_query("DELETE FROM db WHERE `Report No.`= '$id'");
Fix your query by removing single quote of name table:
$result = mysql_query("DELETE FROM db WHERE `Report No.`= '$id'");
Make sure that you type right for Report No. column name. Actually for naming Report No. is not recommended.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've inserted into databases before but never used the 'where' feature. For some reason, it is not inserting, but dieing instead.
<?php
$member=$_SESSION['member'];
$SQL = "INSERT into members where name='$member'(money) VALUES ('100')";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>
This is not valid SQL:
INSERT into members where name='$member'(money) VALUES ('100')
I would assume something like this:
update `members` set `money`=100 where `name`='$member';
Rationale: (money) is a field and 100 is the value for money (since those 2 make the most sense from a INSERT INTO members (field) VALUES (value) syntax point of view).
Never die() with a fixed error message, especially when you can output the actual reason: ... or die(mysql_error()).
But yes, your problem is a syntax error. INSERT queries do NOT have a WHERE clause - where is used to filter records already in the database table. This makes no sense for a new record, because it's not IN the table to filtered in the first place.
You query should basically be just
INSERT into members (name, money) VALUES ('$member', '100')
And note that you are vulnerable to SQL injection attacks, and are using a deprecated/obsolete database interface.
If you want to change existing data, use the update command instead of insert.
You can't use WHERE clause with INSERT command
http://dev.mysql.com/doc/refman/5.0/en/insert.html
You have to do an update
<?php
$member=$_SESSION['member'];
$SQL = "UPDATE `members` SET `money`='100' WHERE `name`='$member'; ";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>
For inserting :
$SQL = "INSERT INTO members(money) VALUES ('100')";
MySQL INSERT Syntax does not support the WHERE clause. MySQL.com Insert Info
Are you actually trying to insert a new row, or update an existing 'member'? If update, then try:
UPDATE members SET money = 100, WHERE name='$member';