I was wondering if it were possible to list all of the ODD ID' using PHP and SQL.
I am currently using, which shows all results:
$result = $con->query("SELECT * FROM Users");
How would it be possible to list only ODD results using PHP and SQL?
thanks in advance..
Or you can do probably faster solution:
$result = $con->query("SELECT * FROM Users WHERE id % 2");
DEMO
You can do,
SELECT * FROM Users WHERE MOD(id,2) = 1
SELECT *
FROM YOUR_TABLE
WHERE (ID_COLUMN % 2) = 1
Related
Is there any way to take the contents of my while query below and use it elsewhere in my php script ?. What I am trying to do is collect the answers from a quiz and then compare them to the correct answers, the problem I am having is that the answers come from one table and the questions from another, so I am currently having to run two different while queries, but I cant use $quiz in the 2nd query as it just stays fixed with the last value it spat out. What im basically trying to do it load table A, look inside for the questionID, select that table and pull out the correct answer. Then load table B, looking inside that, select the answer with the same questionID and then use an if statement to compare to to, so that if correctanswer = actualanswer = correct , and loop over this for each question. The main problem that im coming up against though is the first while pulls out all the correct answers just fine, but I cant then use that in the other while to compare too. Im not sure if this is the correct way of doing it, or if there is a better way ?.
LOOK FOR THE CORRECT ANSWER :
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions
WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answer = $row0['correctanswer'];
}
LOOK FOR THE ACTUAL ANSWER SUBMITTED :
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz
WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
$quiz = $row['quizselectanswer'];
}
Join is propably the best way to do this. But you could also use the php in_array()-Function:
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answers[] = $row0['correctanswer'];
}
And Then
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
if(in_array($row['quizselectanswer'],$answers)){
...correct...
break;
}
}
SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.quizselectanswer = q.correctanswer
Should return all the correct answers. If you also want the wrong answers, you need to do a outer join on the two tables.
I am having some difficulty running some SQL code.
What I am trying to do is, find a row that contains the correct username, and then get a value from that correct row.
This is my SQL in the php:
mysql_query("SELECT * FROM users WHERE joined='$username' GET name")
As you can see, it looks for a username in users and then once found, it must GET a value from the correct row.
How do I do that?
You need some additional PHP code (a call to mysql_fetch_array) to process the result resource returned by MySQL.
$result = mysql_query("SELECT name FROM users WHERE joined='$username'");
$row = mysql_fetch_array($result);
echo $row['name'];
mysql_query("SELECT `name` FROM users WHERE joined='$username' ")
Just select the right column in your 'select clause' like above.
Edit: If you are just starting out though, you might want to follow a tutorial like this one which should take you through a nice step by step (and more importantly up to date functions) that will get you started.
mysql_query("SELECT name FROM users WHERE joined='$username'")
$q = mysql_query("SELECT * FROM users WHERE joined='$username'");
$r = mysql_fetch_array($q);
$name = $r['user_name']; // replace user_name with the column name of your table
mysql_query("SELECT name FROM users WHERE joined='$username' ")
Read documentation : http://dev.mysql.com/doc/refman/5.0/en/select.html
If you don't want to get a full summary of what I'm trying to do skip to (Problem starts here)
I'm setting up my new site and came across a problem.
What I'm basically trying to do is to assign ads to specific countries. So for example if your from the UK you would be shown ads that we have in our UK inventory.
So I gathered some data from Google on how to detect a user's country based on their IP.
I've made a function which does this perfectly.
$ip_address= $_SERVER['REMOTE_ADDR'];
function ip_location($ip){
$parts = explode('.', $ip);
$numeric_ip = $parts[3] + (256 * $parts[2]) + (256 * 256 * $parts[1]) + (256 * 256 * 256 * $parts[0]);
$sql = "SELECT country FROM iptocountry WHERE lower_bound <= $numeric_ip AND upper_bound >= $numeric_ip LIMIT 1";
$result = mysql_query($sql);
$country = mysql_result($result, 0);
return $country;
}
$country = ip_location($ip_address);
echo $country; // Always echos the correct country
(Problem Starts here)
So this function works fine. After making this function I created a MYSQL query which uses the data from that function to select an ad to show a user.
Here is where the problem starts.
When I type this query:
$sql = "SELECT * FROM `nuevo__htmlad` WHERE `country` = 'united kingdom' AND `active` = 1 ORDER BY RAND() LIMIT 1";
using country = 'united kingdom' it works fine but when I put country = '$country'
Nothing works it never displays an ad.
Can anyone help me understand why this query doesn't work when I place the PHP variable inside it. This actually is the first time something this simple has troubled me so much.
Any help would be appreciated.
I avoid this by using a PDO driver for working with databases. This allows me to use parameters and makes it easy to reuse sql statements. Check out this article for more information.
All of the code in the answers provided here contains SQL Injection vulnerabilities. You MUST escape the user input.
http://en.wikipedia.org/wiki/SQL_injection
After asking a few questions in the comments, it turned out that the $country variable contained and additional empty space.
OP fixed it using substr_replace ($country , '' , -1). I would personaly choose trim():
$sql = "SELECT * FROM `nuevo__htmlad` WHERE `country` = '".trim($country)."' AND `active` = 1 ORDER BY RAND() LIMIT 1";
$sql= "SELECT * FROM nuevo__htmlad WHERE country='$country' AND active=1 ORDER BY RAND() LIMIT 1";
or this try this one also
$sql= "SELECT * FROM nuevo__htmlad WHERE country='$country' AND active=1 LIMIT 1 ORDER BY RAND()";
try this one:
I always use this style since country is a string
$sql= "SELECT * FROM nuevo__htmlad WHERE country='".$country."' AND active=1 ORDER BY RAND() LIMIT 1";
I'm new to PHP+MySQL programming
I want to SELCET data using tow constrain at once,
the cons1 is
Tid=user02 and Fid=user01
and cons2 is
Tid=user01 and Fid=user02
the data I want to output is something like:
$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');
+
$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');
= what I want
can it be done in single line?
or can make a result which stored $result1 and $result2
thanks for taking time reading my question
You can OR the two conditions resulting in a single query:
SELECT * FROM chat
WHERE (Tid='user02' AND Fid='user01')
OR (Tid='user01' AND Fid='user02')
$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01' OR Tid='user01' AND Fid='user02'");
Some reading : boolean algebra and the mysql doc
Try this one:
$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01'
UNION SELECT * FROM chat WHERE Tid='user01' AND Fid='user02'");
I have to get records from my MySQL DB where:
sentto = "$username"
OR
sentto = "everyone"
How would I put this in a MySQL query? I tried a few things, but they don't seem to be working:
mysql_query("SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username' || sentto='everyone'");
mysql_query("SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username'
AND sentto='everyone'");
I seem to be stumped, if anyone knows how to do this the right way please let me know. This is a new scenario for me. Thank you!
SELECT *
FROM pmmessages
WHERE sentto = '$username'
OR sentto = 'everyone'
Edit Chris, based on your new query of:
SELECT *
FROM pmessages
WHERE status='unread'
AND sentto='$username'
OR sentto='everyone'
You need to modify it so that your AND stands alone (it is conflicting with your OR).
Rewrite it to this
SELECT *
FROM pmessages
WHERE status='unread'
AND
(sentto='$username'
OR sentto='everyone' )
Taking the detail from one of your comments into account - use the " OR " keyword and parentheses to make sure that the right conditions are combined.
SELECT * FROM pmessages WHERE
status = 'unread'
AND
(sentto = ? OR sentto = 'everyone')
Your problem was never with the OR, though, it was actually the AND precedence and lack of parentheses. The very significant detail that you completely omitted from your question was the additional test for "status = unread".
Note the use of ? above - you should really, really use prepared statements whenever combining MySQL and PHP, i.e.:
$sql = "..." # as above
$sth = $db->prepare($sql);
$res = $sth->execute($username);
while ($row = $sth->fetchrow()) {
...
}
(or the mysqli equivalent)
As it's the same column you're testing, I would use the IN keyword:
SELECT *
FROM pmessages
WHERE status='unread'
AND sentto IN ('everyone', '$username');
The word OR is what you're looking for:
mysql_query("SELECT * FROM pmessages WHERE sentto='$username' OR sentto='everyone'");
is everyone an actual value or do you want to return all results?
if you want to return all results set up something like this
if (#sentto is null)
begin
set #sendto='%'
end
mysql_query("SELECT * FROM pmessages WHERE sentto='$username'")