I am querying a large number of codes from my database, and need to have some validation before a user can input another code in to the database.
An example code would be this:
TD-BR-010212-xxxxxxxx
Where TD represents a promotion, BR represents a place, the numbers represent a date, and the rest are random.
My problem is that before the code is entered into the DB, I want to check to see if the date and place for that code already exists, as they should not be allwed to enter a code from the same place and date.
I assume it would be something within a loop as I already have:
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
But Im just not sure about the best way to check the strings..
You can use a MySQL LIKE clause to get entries in your DB that resemble your code.
Example:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
The '%' is used as a wildcard in SQL LIKE clauses.
You have two approach to solving this issue. Assuming you have access to alter the table.
Add a unique constraint to the table base off of the two columns.
Or Your approach by selecting all of the Location and Date, and see if it return any results.
SQL: SELECT COUNT(*) as counter FROM table where column = 'TD-BR-010212-%'
And check to see if counter return > 0;
I would use the LIKE statement in your SELECT and pull entries that start with the same promotion, place, and date. Unfortunately I don't know how your table looks so bear with me:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
try this query
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
If you can, you'll get better performance and easier coding if you break apart the code into different fields when you save the data in each row. That way you can write queries that specifically check values for the components pieces of the code - you can even set rules in the database (like UNIQUE) to ensure that some parts are kept unique.
Specifically, I'd suggest:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
Your first row would be ([...], 'TD','BR','2012-01-02', 'xxxxxxxx'). And queries would not require unpacking the formatted string - you could say things like "where promotion = 'TD' and place in ('BR','XX') ...". Simple, eh?
Related
I have 12 columns on the below code and I want the best, correct and short way to select only fields for a user order(a row) where the field is not empty/0 in the table.(all fields are INT and numbers are less than 500)
$conn = mysqli_connect("localhost", "root", "","table_name") or die("error");
$sql = "SELECT dqnt_91,deal_91,dqnt_92,deal_92,dqnt_93,deal_93,dqnt_94,deal_94,dqnt_95,deal_95,dqnt_96,deal_96 FROM table_name WHERE fid='$userid' AND COLUMNS ARE NOT EMPTY ";
$result = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$d_91 = $row['deal_91']; $d_92 = $row['deal_92']; $d_93 = $row['deal_93']; $d_94 = $row['deal_94']; $d_95 = $row['deal_95']; $d_96 = $row['deal_96'];
$qnt_91 = $row['dqnt_91']; $qnt_91 = $row['dqnt_92']; $qnt_91 = $row['dqnt_93']; $qnt_91 = $row['dqnt_94']; $qnt_91 = $row['dqnt_95']; $qnt_91 = $row['dqnt_96']; }
echo 'You have selected:'.$d_91.'for'.$deal_91.'<br>';
echo 'You have selected:'.$d_92.'for'.$deal_92.'<br>';
echo 'You have selected:'.$d_96.'for'.$deal_96.'<br>';
Again, I want echo out only those fields that are not zero(0) or empty and if they are zero value then don't show or echo them!
The code below can work but because I have 12 columns and can add more to them then the below code is not handy.
SELECT [ all 12 x columns_name] FROM table_name WHERE table_name.column_name1!='' AND table_name.column_mame2!='' AND x another 10 times the last code ;
Thanks,
Short of modifying the data structure, you won't do much better in SQL than listing the 12 columns each with its own condition; and anything shorter will come at a cost of clarity, so personally I'd advise against it. But if brevity is more important than clarity for your application:
If you can add a view, it could provide a simple flag for you to test against.
create view my_view as (select -- each column
, case when -- all values are present
then 1 else 0 end nonempty_flg
from -- ...)
Then at least the complexity is hidden away from the calling app. If that's not an option:
You state the columns are small integer values. If you can further assume they're non-negative, then you can sum them up and compare against 0. If the might be negative, you could sum their absolute values.
In your examples the columns are treated as strings. If they are in fact CHAR or VARCHAR, you could concat them all and check the result against empty. You might have to coalesce null values to '' as you go.
But it sounds like what you really want is something that works without the query knowing in advance the set of columns; that's not doable in SQL. I suppose you could write a function/method/procedure in your calling program to generate the query based on examining the table columns in the catalog.
Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.
I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is
2, 000002 (which is correct) that is what I am looking for.
$itemId = $_POST['itemId'];
if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
while($data = $sqlItemId->fetch_assoc()){
printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
die();
}
Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.
I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.
$sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");
if($itemId == $sqlItemId){
echo "This item id is already in use. \n";
die();
} else {
echo "Item Id is not in use:";
die();
}
At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?
Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):
$rowsCount = $dbCon->query("
SELECT COUNT(*)
FROM CVCinStoreCoins
WHERE itemId = '$itemId'
");
I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.
Wy don't you just count it,
$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");
if $result > 0
I have a table where I need to find wheter the cell is empty or not.
I don't have the specific column name so I need to display all of the cells that are not empty. (PHP solution would fit too.) Thank you!
Here is my piece of code:
$result1 = mysql_query("SELECT * FROM `FACILITIES` WHERE `room_id` = '{$row['id']}'");
while($row1 = mysql_fetch_assoc($result1)) {
if(empty($row[''])) { //What should I fill in in the $row variable?
alert("Empty");
}
}
I have tried doing in in PHP, but a MYSQL solution would fit too.
You should prevent that problem in the first place. Handle that on DB design level. If you want all your records having values in every column, then define the columns so: not null.
a simple sql that you can rewrite and use would be similar...
sqlfiddle
select * from t where
(col1 is null or col1='')
or
(col2 is null or col2='')
;
sqlfiddle
Anyone who could help me it will be greatly appreciated.
Goal: I want to display the id from one table randomly as well as to make sure it has not been seen by the current user.
Two tables: offers, has_seen
I want to pick a random id from offers, check it against the has_seen table.
If the ID exists in the has_seen, it need to re pick another random id. The same ID should never be seen by any one user of the current session.
I cannot seem to figure out how to pick a random one, check the other table, and loop back if found.
I have tried this
$query = $this->db->query("SELECT * FROM ".$this->offer_table." WHERE NOT EXISTS (SELECT * FROM ".$this->shown_table." WHERE ".$this->shown_table.".camp_id = ".$this->offer_table.".camp_id AND ".$this->shown_table.".usercode = ".$this->session->userdata("table")." LIMIT 1 ");
I think that this can be achieved in plain SQL by doing a left join and then checking for null.
Something along the lines of
SELECT * FROM table1 LEFT JOIN table2 USING (shared_key) WHERE table2.id IS NULL ORDER BY rand() LIMIT 1
Here's how you could do it using CI's db class:
// the maximum ID that is acceptable
$max = $this->db->get('first_table')->count();
while(true) {
// get a random number
$randomID = rand(0,$max);
// the condition for which we will check the has_seen table
$condition = array(
'id' => $randomID
);
// if count is 0, it has not been seen. We add it to the table and return
// if it has been seen, the loop will repeat
if ($this->db->get_where('has_seen', $condition)->count() === 0) {
$this->db->insert('has_seen', array(
'id' => $randomID
));
return $randomID;
}
}
SELECT * FROM `offers` WHERE `camp_id` NOT IN (SELECT `camp_id` FROM `has_seen` WHERE `user code` = 1) ORDER BY RAND() LIMIT 1
I always prefer reading the contents of a table into an array and working with them from there. Depending on how you plan to use the results, you could cut down on db accesses by reading it all only once and then serving from the array (and then, I presume, updating the has_seen table for next session).
I must apologize for the pseudocode as it's been years since I've written any PHP.
Once you've got your array, the algorithm looks like this:
var array
var end = array.length
function getNextRandomUnseen
{
var i = rand(end)
var temp = array[i]
array[i] = array[end--]
return temp
}
If you want, you can even stick the seen values at the end of the array so they aren't lost.
array[end+1] = temp
Thanks for the answers. I redid the way it is going to be brought to the user and believe the new way is much more efficient when it comes to hundreds of people on my site at once.
Thanks!
I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.