PHP Mysql refusing to work with integers - php

OK so I am having trouble figuring out how to retrieve data from mysql using php where i have a variable as an integer.
in database time is (int)11
in phpmyadmin my query is and i get the correct results
SELECT * FROM `transactions` WHERE (`sender` = "f3a8ce96-bfb9-410a-81fb-9deffb7305b2" OR `receiver` = "f3a8ce96-bfb9-410a-81fb-9deffb7305b2") AND `time` >= 1437249470
in php i have
$past = "1437249470";
$user = "f3a8ce96-bfb9-410a-81fb-9deffb7305b2";
$sql = "SELECT * FROM transactions WHERE (sender = '".$user."' OR receiver = '".$user."') AND FROM_UNIXTIME(time) >= $past LIMIT 10";
in php it gives me random and not relevant results
How do i get this to work correctly in php like it does in phpmyyadmin?
example output
phpymadmin:
Quill Littlefeather Josh Piper $275 07/24/15 Object Buy 7/24/2015 7:57:50 AM
php:
Quill Littlefeather Josh Piper $275 04/16/15 Object Buy 4/16/2015 3:41:12 AM
Makes no sence the results should be the same in php as it would be in phpmyadmin.
and yes i know this is not pdo style but pdo is a pain and overly complicated.

The answer to this issue was that i had
$sql = "SELECT * FROM transactions WHERE (sender = '".$user."' OR receiver = '".$user."') AND FROM_UNIXTIME(time) >= $past LIMIT 10";
should be
$sql = "SELECT * FROM transactions WHERE (sender = '".$user."' OR receiver = '".$user."') AND time >= '".$past."' LIMIT 10";

Related

SQL query with results based on current date

I'm practicing on a php website with reservations. I've made three tabs on which I want to display reservations for today and for the coming week.
So far I have this mysql query:
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1
AND reserveringen.datum <= DATEADD(day,+7, GETDATE())";
but I it doesnt display any results
Edit:
I have made an if-else statement saying if there are results display them else echo a message saying "there are no reservations for the coming week". This is the query for showing all reservations and it runs just fine:
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1`
The function name DATEADD() is a TransactSQL function. In MYSQL it is called DATE_ADD() and the parameters are different as well
So this is more likely to work
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1
AND reserveringen.datum <= DATE_ADD(CURRDATE(), INTERVAL 7 DAY)";

wall updates can be seen only by friends

i'm creating a wall system where you can post updates on the index page and i wanted the posts to be seen only by friends of the user, i almost made my code work but i still have a problem ,but before i mention my problem if there is a better way to do it please share it with me , i will show you my code
first i have two tables for the code
'my_friends' : 'id' ,'username','friend'
'statues' : 'p_id','post','f_name','userip','date_created'
this code is in post.php then it will be included in the index page
//Check for user's friends
$check = mysql_query("select * from `my_friends` where `username` = '".$username."' order by `id` desc ");
//Get users friends
while($get_users_friends = mysql_fetch_array($check))
{
$show_more_button = 1;
$result = mysql_query("SELECT *,
UNIX_TIMESTAMP() - date_created AS TimeSpent FROM `statues` WHERE `f_name` = '".mysql_real_escape_string(strip_tags($get_users_friends["friend"]))."' ");
}
while($row = mysql_fetch_array($result))
{
$comments = mysql_query("SELECT *,
UNIX_TIMESTAMP() - date_created AS CommentTimeSpent FROM comments where post_id = ".$row['p_id']." order by c_id asc"); ?>
<div class="friends_area" id="record-<?php echo $row['p_id']?>">
<label style="float:left" class="name">
<b><?php echo $row['f_name']; ?></b><br>
<span>
</span><br>
<em><?php echo $row['post'];?></em>
<br clear="all" />
the code doesn't work right, it show the post feed to only one friend, the first added friend of the user ,in other words , the sql $result = mysql_query("SELECT *,
UNIX_TIMESTAMP() - date_created AS TimeSpent FROMstatuesWHEREf_name= '".mysql_real_escape_string(strip_tags($get_users_friends["friend"]))."' "); select all the statues of only one friend ,when i write echo mysql_real_escape_string(strip_tags($get_users_friends["friend"])),'<br>'; before the sql it shows all the friends but when i use it in the sql it doesn't, please help
Here are some thoughts that maybe can help you
Dont use mysql_* functions they are deprecated use PDO class instead
Dont query for * if you dont need whole the information from the table
Table name is statues
After completing first while your variable $result will hold only the last friend data query cause it gets overritten by the next step of iteration(use $result[] = )
Aggregate info from $get_users_friends to rewrite your query into SELECT p_id, post, f_name, UNIX_TIMESTAMP() - date_created AS TimeSpent FROM statues WHERE f_name IN '.implode(',', $firends_name).
Dont see if you use $comments variable at all
$show_more_button = 1; dont see if it is used at all. and ofc it gets overritten by next iteration step;
your code should look something like:
$check = mysql_query("select friend from `my_friends` where `username` = '".$username."' order by `id` desc ");
while($get_users_friends = mysql_fetch_array($check, MYSQL_ASSOC))
{
$result[] = $get_users_friends['friend'];
}
$friends_data_query = mysql_query("SELECT p_id, f_name, post,UNIX_TIMESTAMP() - date_created AS TimeSpent FROM `statues` WHERE `f_name` IN'".implode(',',$result)."'");
while($friends_data = mysql_fetch_array($friends_data_query,MYSQL_ASSOC)){
But make sure that it is rewritten into PDO. Cause now it is very vulnurable to injections.

Combining queries for speed

I started using only 1 query but then I wanted some to show up more than others so I ended up doing more queries but it, really slows down the load time, is there a way I can do them all in a single query but have them all with their separate variable name?
$sql23 = "SELECT * FROM monsters WHERE rare='0' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$result23 = mysqli_query($link,$sql23) or die(mysqli_error());
$battle_get23 = mysqli_fetch_array($result23);
$boss = "SELECT * FROM monsters WHERE rare='1' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$boss = mysqli_query($link,$boss) or die(mysqli_error());
$boss = mysqli_fetch_array($boss);
$rare1 = "SELECT * FROM monsters WHERE rare='2' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare1 = mysqli_query($link,$rare1) or die(mysqli_error());
$rare1 = mysqli_fetch_array($rare1);
$rare2 = "SELECT * FROM monsters WHERE rare='3' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare2 = mysqli_query($link,$rare2) or die(mysqli_error());
$rare2 = mysqli_fetch_array($rare2);
$rare3 = "SELECT * FROM monsters WHERE rare='4' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare3 = mysqli_query($link,$rare3) or die(mysqli_error());
$rare3 = mysqli_fetch_array($rare3);
$rare4 = "SELECT * FROM monsters WHERE rare='5' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare4 = mysqli_query($link,$rare4) or die(mysqli_error());
$rare4 = mysqli_fetch_array($rare4);
$rare5 = "SELECT * FROM monsters WHERE rare='6' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare5 = mysqli_query($link,$rare5) or die(mysqli_error());
$rare5 = mysqli_fetch_array($rare5);
$rare6 = "SELECT * FROM monsters WHERE rare='7' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare6 = mysqli_query($link,$rare6) or die(mysqli_error());
$rare6 = mysqli_fetch_array($rare6);
$rare7 = "SELECT * FROM monsters WHERE rare='8' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare7 = mysqli_query($link,$rare7) or die(mysqli_error());
$rare7 = mysqli_fetch_array($rare7);
$rare8 = "SELECT * FROM monsters WHERE rare='9' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare8 = mysqli_query($link,$rare8) or die(mysqli_error());
$rare8 = mysqli_fetch_array($rare8);
$rare9 = "SELECT * FROM monsters WHERE rare='10' AND level<='".$row['level']."' ORDER BY RAND() LIMIT 1;";
$rare9 = mysqli_query($link,$rare9) or die(mysqli_error());
$rare9 = mysqli_fetch_array($rare9);
First. You are barking the wrong tree.
Combining a number of slow queries in one won't make them fast. Overhead for running a query is NOT that important as most php users think. If query itself is fast, no matter how many times it is called (within sane numbers of course). If query is slow, no combining would help.
You have to take care for the queries themselves instead of trying to combine them. Thus, to solve your problem you have to provide a lot more info:
Define "really slows" in certain numbers. For all queries in one and for the every single query.
Provide database schema and data amounts.
Provide result of one of the queries run perpended with EXPLAIN keyword
You could give your monsters a random number once a day or once an hour, so
update monsters set sortorder=rand();
It might help to have an index on that key sortorder.
Then you could calculate for every read a random number in php:
$rand = mt_rand(0,1); // or however mt_rand() is called
Then you could select:
$sql23 = "SELECT * FROM monsters WHERE rare='0' AND level<='".intval($row['level'])."' ORDER BY (sortorder-$rand) DESC LIMIT 1;";
$result23 = mysqli_query($link,$sql23) or die(mysqli_error());
$battle_get23 = mysqli_fetch_array($result23);
From SQL it is easy to create a solution with only one select, but that needs a temporary table to support undisturbed random.
Use a category-table
CREATE TABLE raretype (id int(11), name varchar(255), sortkey float default 0, primary key(id));
Put your rares in there:
INSERT INTO raretype (id, name) values (0, 'battle_get23'),(1,'boss'),(2,'rare1'),...
Create a random sortorder for your read:
DROP TEMPORARY TABLE IF EXISTS tmp_rare_sort;
CREATE TEMPORARY TABLE tmp_rare_sort (raretype int(11) not null primary key, sortorder float);
INSERT INTO tmp_rare_sort SELECT id, rand() from raretype;
Read them out:
SELECT rt.name as type, m.*
FROM raretype rt
INNER JOIN tmp_rare_sort rts on rts.raretype = rt.id
LEFT JOIN monsters m on m.id =
( select id from monsters imo where imo.rare = rt.id
and imo.level <= {intval($level)}
order by abs(sortorder - rts.sortorder) desc
limit 1
)
You should read out an array as a result:
$allMonsters = array();
while($line = $rs->next()){
$allMonsters[$line['type']] = $line;
}
So that $allMonsters['boss'] gives the boss (with an additional field 'type', that should not hurt).
If you really want it as single variables, you could extract() this array.
Hope that helps!
If some syntax errors, please create a SQL-fiddle and I'll check. Just no time to create the tables myself. ;-)
1) take out all of your order by RAND() and limit 1
2) do randomization after query
$bossSql = "SELECT * FROM monsters WHERE rare='1' AND level<='".$row['level']."' ";
$bossRs = mysqli_query($link,$bossSql) or die(mysqli_error());
$bossArray = mysqli_fetch_array($bossRs);
//just saw you had limit in your sql, edited
//shuffle($bossArray);
$randomBosskey = array_rand($bossArray);
$randomBoss = $bossArray[$randomBossKey];
edit: thank you #flaschenpost for pointing out the potential problem, which inspired me to come up with a possibly quicker solution (under certain assumption which might not be true)
Solution 2) cache the table
From the looks of the code I think there is a high chance that you would need to do the query for monster action many times throughout the whole program lifetime.
Instead of getting a new random monster from DB everytime, will it be better to do full query:
SELECT * FROM monsters
save it in a variable and then pick the a random monster according to rarity and level from the same variable everytime you need a monster? But this method takes up unknown amount of memory depends on your table size and might be faster/slower than your original depending on how many "random monster" query you are actually using in your program. It might also depends on the "power" of your machine, assuming your DB and server are not in the same machine and the 2 machine have significant difference in processing power.

Edit php string

I have a string that makes a function from my order status. I wan´t to have it to trigger with 2 order status´
Is that posible?
$query = "SELECT * FROM #__redshop_orders where order_payment_status ='Paid' and order_status = 'RD2'";
So insted of just trigger with status RD2 it should trigger with RD1+RD2
Plus - I wan´t to remove the order_payment_status function, so it only triggers for order status.
How will the string look like after editting?
Thank you.
It would be something like this:
$query = "SELECT * FROM #__redshop_orders WHERE order_status = 'RD1' OR order_status = 'RD2'";
You should try to learn MySQL, a simple google search would give you plenty of example and tutorials.
EDIT:
I made some tests since I posted my answer, and the benchmarks show that a much faster solution would be:
$query = "SELECT * FROM #__redshop_orders WHERE order_status IN ('RD1', 'RD2')";
$query = "SELECT * FROM #__redshop_orders WHERE order_status IN ('RD1', 'RD2')";
$query = "SELECT * FROM #__redshop_orders where order_status IN('RD1','RD2')";
//You want this

Getting total in while statement with UNION query

I am trying to calculate how much a user has earned so it reflects on the users home page so they know how much their referrals have earned.
This is the code I have.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
$countr_cash = $get_ref_cash->fetch_assoc();
$total_cash += $countr_cash['cash'];
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
It worked fine when I just had
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."'");
but as soon as I added in the UNION it no longer calculated correctly.
For example, there is 1 entry in completed and 1 entry in completed_repeat both of these entries have a cash entry of 0.75. The variable for $countr_c_rate is 0.10 so $total_cash should equal 0.15 but instead it displays as 0.075 with and without the UNION it acts as if it is not counting from the other table as well.
I hope this makes sense as I wasn't sure how to explain the issue, but I am very unsure what I have done wrong here.
In your second query instead of UNION you should use UNION ALL since UNION eliminates duplicates in the resultset. That is why you get 0.075 instead of 0.15.
Now, instead of hitting your database multiple times from client code you better calculate your cash total in one query.
It might be inaccurate without seeing your table structures and sample data but this query might look like this
SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = ?
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = ?
) q
Without prepared statements your php code then might look like
$sql = "SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = '$user_info['username']'
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = '$user_info['username']'
) q";
$result = $db->query($sql);
if(!$result) {
die($db->error()); // TODO: better error handling
}
if ($row = $result->fetch_assoc()) {
$total_cash = $row['cash_total'] * $setting_info['ref_rate'];
}
On a side note: make use of prepared statements in mysqli instead of building queries with concatenation. It's vulnerable for sql-injections.
With $countr_cash = $get_ref_cash->fetch_assoc(); you only fetch the first row of your result. However, if you use UNION, you get in your case two rows.
Therefore, you need to iterate over all rows in order to get all values.
Ok, So there is only one row in members table. You are iterating only once on the members table. Then you are trying to get rows using UNION clause which will result in two rows and not one. Then you are just getting the cash column of the first row and adding it to the $total_cash variable.
What you need to do is iterate over the results obtained by executing the UNION query and add the $total_cash variable. That would give you the required result.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
while($countr_cash = $get_ref_cash->fetch_assoc()){
$total_cash += $countr_cash['cash'];
}
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}

Categories