php mysql query with multiple conditions - php

I need the mysql query to get the items whose nid > 910 for user_id=1 and nid > 902 for used_id <> 1.
Anybody done this? Searched but cant find it, since i am new to php and mysql.

Can't you use OR in your WHERE criteria:
SELECT *
FROM YourTable
WHERE (nid > 910 AND user_id = 1)
OR (nid > 902 AND user_id <> 1)

Try with this query:
SELECT * FROM items WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1)

SQL Query:
SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);
But if you want to call it from PHP you'll need something like this:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("exampledb",$dbhandle)
or die("Could not select exampledb");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'user_id'}." Nid:".$row{'nid'}."<br />";
}
?>

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

second sql query based on the first one

i want to take the result of an sql query "user_id"and search using it in
in another query in another table
for example :
main query select * from tracker
second query: take the id from the first query to replace it with the name of the user found in another table "user table".
something like :
select user_name from vtiger_users where id = $row["id"]
here is my code below
<?php
$servername = "localhost";
$username = "x";
$password = "xyz";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, module, whodid,changedon FROM vtiger_modtracker_basic";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table style='float: left'><tr><th>ID</th><th>Module</th><th>Who Did</th><th>Time Of Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$user_id=$row["id"];
$username_sql="SELECT user_name FROM vtiger_users where id=".$user_id." ";
$result_username=$conn->query($username_sql);
$row2 = $result_username->fetch_assoc();
echo "<tr><td>".$row["id"]."</td><td>".$row["module"]."</td><td>".$row2["user_name"]."</td><td>".$row["changedon"]."</td></tr>";
//echo "<p>".$row2["user_name"]."</p>"
//echo $row2["user_name"];
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I guess you should use whodid column when you set $user_id = $row['whodid'] or you can use JOIN query. It will return you user_name from vtiger_users table.
SELECT
a.id,
a.module,
a.whodid,
a.changedon
b.user_name
FROM vtiger_modtracker_basic a
JOIN vtiger_users b ON a.whodid = b.id
thanks all ,that query did the job for me
SELECT vtiger_modtracker_basic.id, vtiger_modtracker_basic.module, vtiger_modtracker_basic.whodid ,vtiger_modtracker_basic.changedon ,vtiger_users.user_name FROM vtiger_modtracker_basic ,vtiger_users where vtiger_modtracker_basic.whodid = vtiger_users.id

INNER JOIN SQL Query not working with PHP

I have created two tables in my database and normally my php file is able to get table data from mysql.
But when I add INNER JOIN or anything like that, it does not work anymore. No output is seen but also no error message (so the code have to be correct, I think).
Here's my php code:
<?php
$db_name = "mydatabase";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
mysqli_close($conn);
?>
Try to debug like
1.if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
2.$query = mysqli_query($conn,"SELECT * FROM firsttable INNER JOIN secondtable ON firsttable.secondtable_id = secondtable.secondtable_id");
if (!$query) {
die('Invalid query: ' . mysql_error());
}
It seems there is no error in your program ! Make sure the database connection is established or not
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
The mysql query seems to be correct .. better you post your database structure ! and check the column name
firsttable.secondtable_id = secondtable.secondtable_id
in your code both are secondtable_id, is that correct column name ?

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

MYSQL does not return result in PHP when asked for the first ranking only

I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;

Categories