How to check if string exists in more than X rows - php

I would like to know if the following is possible, and how:
I want to check if a username in my table appears in 5 or more rows
my table:
Example of usage that I want:
If the name (teste) is on more than 5 rows then do something..

Use HAVING, it allows you to filter by aggregated / manipulated fields
SELECT count(username) as shows_counter from tbl
group by username
HAVING count(username)>5
$check = mysql_query("SELECT count(name),name
FROM hack_log group by name HAVING count(name)>5");
$check = mysql_num_rows($result);// **Add this row**
if($check){ echo "HACKER!"; }else{ echo "not hacker"; }
Please use PDO or mysqli build-in objects
Accorging to your needs
You need to check number of rows
$db = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$q = $db->prepare('SELECT count(name),name
FROM hack_log group by name HAVING count(name)>5');
$q->execute();
$rows = $q->fetchAll();
$res= count($rows)>0?"Hacker":"No Hacker";
echo $res;

Related

Comparing input data with data queried from database

So when I tried to get one random row in database and store it into variables, it seems like I cannot reuse those variables for my next sql query as I was tried in these lines.
First I get one random row in database and store it into variables for later use
$mysqli = new mysqli($hostname, $username, $password, $dbname, $port) or die(mysqli_error($mysqli));
$sqlcompare = "SELECT * FROM questions order by rand() limit 1";
$result = mysqli_query($mysqli, $sqlcompare);
$row = mysqli_fetch_row($result);
$pos = $row[0];
$word = $row[1];
$pos is the id of that row $word is the data of that row.
Then I get user input and checking the database if there is a row both have the same id with $pos and the input word is the same as that row
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word = $input AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
if (isset($_POST['compare'])) {
if (mysqli_num_rows($sqlresult)>=1) {
echo "Found that input";
} else {
echo "Not found";
}
}
When I tried to retrieved word from database directly from user input, which only have one condition, the code work perfectly but when I add id condition in, it not working anymore. Any idea where I screw thing up?
Edit note: I just tried to echo $pos and $word and it work perfectly but somehow when I tried to put $pos varibale into sql to query, it does not working.
Use like instead of ( = ).
$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word LIKE '%".$input."%' AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
Mysql Like docs

SELECT statement returns first row instead of record that is looked up

I am trying to select a record from my database, and I am return instead the first one in the table. No matter what I try, the first one gets returned.
Here's the query:
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
Then I try a test to see the value that is returned as such:
echo $response or die(mysql_error());
This is where I see the user_id of the first row.
Even if I try to put a specific value in the query, as follow, I am getting the same result:
$query_task_owner = "select user_id from users where full_name = 'LeBron James'";
I do not understand because when I trying this query directly in PHPMyAdmin, I am getting the right result. So the query itself is correct.
Any idea?
Fetch $response using mysqli_fetch_array().
<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
$row = mysqli_fetch_array($response,MYSQLI_ASSOC);
echo $row['user_id'];
?>
If, users are more related to that full name. Then, use while loop to fetch all record.
<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
while($row = mysqli_fetch_array($response,MYSQLI_ASSOC))
{
echo $row['user_id']."<br>";
}
?>

How to echo the result of count(*) AS in PHP?

I am using the count(*) AS, as an alternative to mysql_num_rows().
I get a count for all 3 kinds of feedback (positive, negative and neutral).
But I don't know how to assign the count of, say, positive feedback to a variable that I would call $positive_feedback and then, echo it. How can you do this with the following example?
I have this:
SELECT feedback, count(*) AS `count`
FROM feedback
WHERE seller='$user'
GROUP BY feedback
which gives something like that:
feedback | count
----------------
positive | 12
neutral | 8
negative | 3
$result = mysql_query($query); // with your query.
$feedback=array();
while ($row = mysql_fetch_assoc($result)) {
$feedback[$row['feedback']]=$row['count'];
}
It will give an array consisting of feedback['positive'],feedback['negative'] and so on with count stored in each.
Use Count(1), not Count(*), it's faster because the SQL engine can just use the count values from the counting B-Tree index and does not need to ever access any other values. If you plan to make this query a lot, make sure you add an index on the feedback tuple.
$query = "SELECT feedback, count(1) AS `count`...";
$result = mysql_query($query, $link); // don't forget to share your db conn
$feedbackArr = new array();
while ($row = mysql_fetch_assoc($result)) {
$feedbackArr[$row['feedback']] = (int)$row['count'];
}
echo "Positive Feedback: \n";
print_r($feedbackArr);
With PDO it will look something like this:
$dsn = "mysql:host=%;dbname=%"; // insert your host and dbname
$db = new PDO($dsn, $username, $password); // insert your username and pass
$sql = "
SELECT
feedback, count(*) AS `count`
FROM
feedback
WHERE
seller='$user'
GROUP BY feedback
";
$feedback = array();
foreach ( $db->query($sql) as $row ) {
$feedback[ $row['feedback'] ] = $row['count'];
}
// result in here
print_r ($feedback);

MySQL query WHERE statement which is a query itself?

So I'll try to clearly explain my goal first:
First, I want to query one table in my database for a list of usernames.
Second, I want to take those usernames, and query another table in the database and return only the rows in which these usernames appear in the username field.
Finally, I want to take this output (in JSON array form right now), and return it to the requesting client.
My query looks like this right now:
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
This works when the WHERE statement yields 1 result. So if I only get one returned userA, it works fine. But if I get multiple, I get a bunch of errors.
Here is the code in its entirety:
if (isset($_POST['username'])) {
$username = $_POST['username'];
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("TagDB");
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
}
while ($e = mysql_fetch_assoc($query)) {
$output[] = $e;
}
$output = json_encode($output);
print $output;
I get the following error on the query line:
*Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\wamp\www\tag\appgetfriendinfo.php on line 21*
So all I really need to know is, how would I write that query in MySQL so that I get returned an array of rows?
You don't need a subquery at all, you'll usually get better performance out of a join. Make sure you have indexes defined on tagusers.username, friendtable.userA and friendtable.userB
SELECT
tagusers.*
FROM
tagusers
INNER JOIN
friendtable
ON
tagusers.username = friendtable.userA
AND
friendtable.userB = '$username'
Use the IN keyword.
$query = mysql_query("SELECT * FROM tagusers WHERE username IN
(SELECT userA FROM friendtable WHERE userB = '$username')");
Use either the IN clause, or a JOIN like in this example:
$query = sprintf("SELECT tu.*
FROM TAGUSERS tu
JOIN FRIENDTABLE ft ON ft.usera = tu.username
WHERE ft.userB = '%s'",
mysql_real_escape_string($_POST['username']));
$result = mysql_query($query);
$output = json_encode($result);

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories