I'm using the following code:
$con = mysql_connect("NOTGIVEN","NOTGIVEN","NOTGIVEN");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("user_live", $con);
$result = mysql_query("SELECT * FROM user_new_post ORDER BY user_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user_full_name']);
}
And instead of selecting the table/row user_new_post how can I be able to select individual values "users" and then print/echo them out?
Either you have another table "user" on which you can use
SELECT * FROM user
or you can use a WHERE clause
SELECT * FROM user_new_post WHERE user_full_name like 'a%' ORDER BY user_date_post DESC
to get all user full name starting with 'a'
You may perform a search for exactly a user name like this:
$result = mysql_query("SELECT * FROM user_new_post WHERE user_name= '".$user."'");
Or perform a regular expression in the query to search for user's name match your pattern:
$result = mysql_query("SELECT * FROM user_new_post WHERE user_name REGXP '".$pattern."'");
Or use like keywork provied by MySQL:
$result = mysql_query("SELECT * FROM user_new_post WHERE user_name like '".$user."'");
Related
i want to pass limit value in my select query through user,can anybody help me to do this???? thanks in advance![][1]
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created ", $con);
lets just say that the user input is "LimitInput" then :
$limit = $_POST['LimitInput'];
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created limit 0,".$limit, $con);
$result = mysql_query("SELECT DISTINCT *
FROM tweet_info
WHERE MATCH(tweet)
AGAINST('" . $search . "')
ORDER BY created LIMIT 0,1 DESC", $con);
Just add a limit to the end, this will grab the first result found.
You shouldn't really be using the mysql_query function anyway, it's depreciated, maybe look into a different method, e.g. mysqli or PDO.
I'm querying one database to get product stockcodes related to a news article
$result = mysql_query('
SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"');
then I need to use the data taken from the stockcode column to query a second database. I'm using
$rows = mysql_fetch_array($result);
to put the info in to an array. How do I use that array in the second mysql query?
$also_result = mysql_query("SELECT * FROM WebProducts
WHERE WebProducts.stockcode THE ARRAY GOES HERE AND WebProducts.visible='Y'") or die(mysql_error());`**
Sounds like a simple join for me.
mysql_query("SELECT * FROM WebProducts p
JOIN news_related n
ON p.stockcode = n.stockcode
WHERE n.news = " . $news_id . "
AND p.visible='Y'");
Tr in a single query like,
$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN
(SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
AND WebProducts.visible="Y")');
From your approach it should be like,
$arrStock=array();
while($rows = mysql_fetch_array($result))
{
$arrStock[]=$rows['stockcode'];
}
if(!empty($arrStock))
{
$also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'");
}
You know about the second parameter in mysql_query() which is connection identifier, in your case there are two databases so you should have 2 connections like $con1 and $con2
$result = mysql_query('SELECT * FROM WebProducts WHERE WebProducts.stockcode IN
(SELECT stockcode FROM news_related WHERE news = "'.$news_id.'"
AND WebProducts.visible="Y")',$con1);// use $con1 for first db
and in the second query
$also_result=mysql_query("SELECT * FROM WebProducts WHERE WebProducts.stockcode
IN (".implode(',',$arrStock)." AND WebProducts.visible='Y'",$con2);
// use $con2 for second db
Also the mysql_ is deprecated and will removed in the upcoming versions of PHP so use mysqli_*
I have a MySQL database and I need a PHP to pull a random row. I have successfully created
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
This successfully randomly pulls a row; however, it is not limited to where region=2.
I need to be able to:
pull randomly when region=UK
pull randomly when region=UK or ##
(where ## is actually another region, for example, YK = Yorkshire)
Basically I need it to select rows randomly but ONLY when region=UK.
region is a label for one of my fields/collumns, and UK is the content of the VARCHAR in that for a number of rows.
I have the rest of the code sorted.
I have a simple database and the php as follows:
<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="carbonmarketing.db.9606426.hostedresource.com";
$username="MarketReadOnly";
$password="Read0nly1";
$dbname="carbonmarketing";
$usertable="ClientList";
$advertfooter = "advertfooter";
mysql_connect($hostname,$username, $password) or die ("<html>%MINIFYHTML4333ddb1f6ba50276851b9f9854a5c817%</html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
$advertfooter = $row["$advertfooter"];
echo "$advertfooter";
}
}
?>
But, it's just pulling randomly for all values of the region column
Let me know if it would help for you to see the database.
Make and array with your regions and implode them:
$region = array('UK', 'YK');
$implode = implode("', '", $region);
$query = "SELECT * FROM `".$usertable."` WHERE `region` IN ('".$implode."') ORDER BY RAND() LIMIT 1";
$query = "SELECT * FROM $usertable
WHERE region IN ('UK','YK')
ORDER BY RAND() LIMIT 1";
I was trying to get some details from MySql database, but i was working so long and tried so many ways that i am completely lost now :s
What i need to GET is two details which depend on information from 3 tables. I need to get $title and $siteurl (from table_sites) where current user did not click it before, AND siteurl owner still have remaining credits...
Here is my database:
USER:
id
username
password
credits
active
clicks
SITES:
id
userid
title
siteurl
clicks
active
weight
CLICKS:
id
siteid
byuserid
i tried with this MySql query:
include('db_con.php');
mysql_connect("$dbhost", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$qrym = mysql_query("SELECT * FROM `users` WHERE username='$username' LIMIT 1") or die (mysql_error());
while($mem = mysql_fetch_object($qrym)){
$uid = $row->id;
}
$qrys = mysql_query("SELECT * FROM sites, clicks WHERE clicks.byuserid != '$uid' and sites.userid != '$uid' and sites.active = '1' ORDER BY sites.weight DESC, sites.id DESC LIMIT 1") or die (mysql_error());
if(mysql_num_rows($qrys)!=0){
while($row = mysql_fetch_object($qrys)){
$title = $row->title;
$siteurl = $row->siteurl;
echo "$title $siteurl";
}
} else {
echo "No more sites";
}
No errors, but whatever i try result is No more sites! How to JOIN this query correctly?
Maybe do
while($row = mysql_fetch_object($qrym)){
$uid = $row->id;
instead of
while($mem = mysql_fetch_object($qrym)){
$uid = $row->id;
You probably want a query like this:
SELECT [the columns you need]
FROM sites
LEFT JOIN clicks ON clicks.siteid = sites.id
AND clicks.byuserid = [current user id]
WHERE sites.active = 1 AND clicks.id IS NULL
ORDER BY sites.weight DESC, sites.id DESC
LIMIT 1
As gpojd noted above, you must must MUST sanitize your inputs before using them in a query. Fix your first query's code:
$qrym = mysql_query("SELECT * FROM `users`
WHERE username='" . mysql_real_escape_string($username) . "' LIMIT 1");
When fetching only a single row, as your first query does, there is absolutely NO need for a while() loop to retrieve the data.
That, and observe the comments in the code block:
$qrym = mysql_query("SELECT * FROM `users` WHERE username='$username' LIMIT 1") or die (mysql_error());
while($mem = mysql_fetch_object($qrym)){
^^^--- you fetch into $mem
$uid = $row->id;
^^^--- but try to retrieve from $row?
}
Try this instead:
$sql = "SELECT ...";
$qrym = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($qrym);
$uid = $row['uid'];
I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.