Show records in the table with if - PHP - php

I have a plant table and a customer campaign table, I want to show only plants that are not associated with the customer campaign table.
through this if cycle, I would like to get a solution like if it is true not to show the plants that are associated if and it is false shows the plants that are not associated
it's possible?
<?php
session_start();
include 'connessione.php';
$var = true;
$var = 1;
$query = mysqli_query($connessione, "
SELECT *
FROM store_locator
INNER JOIN campagne_cliente
ON store_locator.id = campagne_cliente.impianto_id_campagna");
if (!$query)
{
die('Error: ' . mysqli_error($connessione));
}
if($var === true){
echo "email already exists";
}else{
echo "ok";
}
?>
but if i have only plants associated and nothing plants free i have always ok.
Why?

Correct:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM store_locator WHERE store_locator.id NOT IN (SELECT impianto_id_campagna FROM campagne_cliente);
";
$query = mysqli_query($connessione, $query_string);
?>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<?php echo $row['id'] ;?>
<?php } ?>

USE NOT IN QUERY LIKE THIS....
AM Just Try to understand you,you can manage it according to your table structure.
SELECT * FROM `plant_table` not in (select customer_campaign.plant_id from customer_campaign);
Hope This will Help You.
Thanks
I got this result:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'not in (select campagne_cliente.impianto_id_campagna from campagne_cliente)' at line 2
this is a query:
SELECT * FROM `store_locator`
not in
(select campagne_cliente.impianto_id_campagna
from campagne_cliente);

Related

How to use GROUP BY method in php-mysql

I’m trying to use "group by" instead of "DISTINCT" in my php file to select some rows that all of them have an specific column value and it’s "idchat".
And I want to get more than one columns
please help me!
I’ve checked every pages but I didn’t understand enything
<?php
$connection = mysqli_connect("localhost","---","pass","---");
$id = $_GET["id"];
$mobile = $_GET["mobile"];
$idchat = $_GET["idchat"];
if (strpos($mobile, '9') !== false) {
$query = "SELECT DISTINCT a,b,c,d,idchat FROM database where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
}
mysqli_close($connection);?>
and this code gives me this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/---/test.php on line 12
See next output:
mysql> SELECT * FROM database;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database' at line 1
mysql> SELECT * FROM mytable;;
ERROR 1146 (42S02): Table 'test.mytable' doesn't exist
ERROR:
No query specified
mysql>
The first query is not understood because database is a reserved word. You should not use that to name a table. A work around is to add backquotes around the name:
mysql> SELECT * FROM `database`;
ERROR 1146 (42S02): Table 'test.database' doesn't exist
mysql>
"Could you correct my codes please?": Ok, but untested:
<?php
$connection = mysqli_connect("localhost","---","pass","---");
$id = $_GET["id"];
$mobile = $_GET["mobile"];
$idchat = $_GET["idchat"];
if (strpos($mobile, '9') !== false) {
$query = "SELECT DISTINCT a,b,c,d,idchat,id FROM `database` where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
}
else {
echo mysqli_error($connection);
}
mysqli_close($connection);?>
}
I also did add id to the query because of comment from #Raymond

Joining two table and updating the result

I am joining two table and I want to update all the rows.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id, students.ID
FROM course, students
where course.id=course_id and course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
echo "$id</br>";
}
}
?>
I tried the Select Statement above in "Run SQL query" and it query the result i want. and I want to update all of the query, but I cant. I tried Putting echo under the update and it echo the ID's I need to update, but my update statement is not executing.
Instead of selecting all students then updating one by one, you can actually to this in one shot by joining both tables and updating it.
UPDATE students s
INNER JOIN course c ON c.id = s.course_id
SET s.Year = '$Graduated',
s.Status = 'non-Active'
WHERE c.duration = '2'
AND s.status = '$stat'
AND s.Year = '$year'
It must also be taken into consideration that the query above is vulnerable with sql injection. This article below will guide you how to prevent from it.
How to prevent SQL injection in PHP?
The issue with the first query is that there are two columns with the same name; ID. So referencing the ID from the row generates an error. Use alias to fix it as shown below. For a better performance use an inner join instead. You also forgot to run the update query again your database.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id as cID, students.ID as sID
FROM course JOIN students ON course.id=course_id
where course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['sID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
echo "Student ID to be updated: $id<br/>";
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
//you have to execute the query for the update to be done.
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully ";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
$conn->close();
?>

Subqueries for php

sorry if this might be a duplicate question but im desperatly needs help for project submission.
I have a database carpark where i have 2 table within which is carpark_availability and history.
From my code, im able to get a field "development" from table carpark_availability.
I would like to ask on how to structure my queries if i want to select * from c where my h.development = c.development.
As shown below is my code:
<?php
session_start();
$con = new mysqli('localhost','root','','carpark_project');
$dev = $_SESSION["development"];
echo "Development: ";
echo $dev;
$sql = "select * from carpark_availability where
carpark_availability.Development IN (select history.development
from history where
history.Development = '$dev' )";
//$sql = "select * from carpark_availability where development = '$dev'";
//$sql = "select * from carpark_availability where (select Development
//from history where Development= '$dev'";
$result = $con->query($sql);
while($row = $result ->fetch_assoc())
{
echo "Development: ";
echo $row["Development"]. "</br>";
echo $row["Area"]."</br>";
echo $row["weekday1"]."</br>";
}
?>
A join is much easier on the eye than a subquery.
SELECT c.*
FROM carpark_availability c
INNER JOIN history
USING (development)
GROUP BY development;
I'm guessing you are getting an error because your query is returning no results so $result is set to boolean false. You have nothing in your code to check for that so you are trying to call fetch_assoc() on it

Join two MySQL tables with PHP

For example, I have created two pages and two MySQL tables.
Index.php & citys.php
citys
ID City Country Population
--------------------------------------
1 Amsterdam NL 1500000
2 Rotterdam NL 900000
3 Dusseldorf DE 1800000
comments
ID City Name Comment
---------------------------------
1 Dusseldorf Jack Great city!
2 Dusseldorf John Beautiful
3 Rotterdam Emy Love it
At the moment I only use the table citys like this:
index.php linking to citys.php with:
<a href='citys.php?cmd=menu&id=";echo $row['id'];echo "'>
And citys.php use this code to show the data from MySQL:
<?php
include "connect.php";
if(!isset($cmd))
{
if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
{
if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT * FROM citys WHERE id=$id";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
<?php echo $row["City"] ?>
<br><br>
<?php echo $row["Country"] ?>
<br><br>
<?php echo $row["Population"] ?>
Until here everything is showing up and working fine.
But I also want to show the comments on page 2. So the query has to be edited to also get the right data from the table comments.
I tried different examples from internet that I have edited myself like:
<?php
include "connect.php";
if(!isset($cmd))
{
if($_GET["cmd"]=="menu" || $_POST["cmd"]=="menu")
{
if (!isset($_POST["submit"]))
{
$id = $_GET["id"];
$sql = "SELECT citys.*, comments.* FROM citys, comments WHERE citys.id=$id AND comments.city=citys.city";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
But nothing works.
How can I fix this?
The query from VIPIN JAIN's answer works, but there is one problem left:
Query:
$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";
If the table 'comments' has three rows, this code shows only the last two but not the first:
<?php
while($row = mysql_fetch_array($result)) {
echo "<br><br>";
echo $row['name'];
echo "<br>";
echo $row['comment'];
}
?>
And if I try this it only shows the first row.
<?php echo $row["name"] ?>
<br>
<?php echo $row["comment"] ?>
I don't know why the first record is left away in the loop.
Use this query
$sql = "SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";
Use leftjoin for this type of work
select * from citys
left join comments on comments.city = citys.city
where citys.id=$id

Echoing users by group name in PHP

What I want to do is click a name of a group(every group what I create other than poweruser and admin groups) and that will echo all of the users in that group from the database. I have figured out the code so far but now my problem is how will I print it all out when clicking the name of the group?
My code so far is:
<h3>Groups</h3>
<?php
include('db.php');
if (isset($_GET["groupID"])) {
$sql="SELECT `group`.*, `user`.* FROM `user` inner join `group` on group.groupID=user.groupID where group.groupID= " . mysql_real_escape_string($_GET["groupID"]) ;
} else {
$sql="SELECT * FROM `group` WHERE groupName <> 'admin' AND groupName <> 'poweruser'" ;
}
$result=mysql_query($sql,$connection);
while($line=mysql_fetch_array($result)){
echo "<a href='index.php?page=groups&group=".$line['groupID']."'>".$line['groupName'].'</a><br />';
}
mysql_free_result($result);
mysql_close($connection);
?>
On top of the $_GET["group"] issue, it doesn't look like you're printing out the users anywhere.
You should move the output into the if block, and create new output for the first condition.
<?php
include('db.php');
if (isset($_GET["groupID"])) {
$sql="SELECT `group`.*, `user`.* FROM `user` inner join `group` on group.groupID=user.groupID where group.groupID= " . mysql_real_escape_string($_GET["groupID"]) ;
$result=mysql_query($sql,$connection);
//Output users after Group Selected
//Could be placed outside the if block to allow user to select a different group
echo("<h3>Users</h3>");
while($line=mysql_fetch_array($result)){
//echo out the user data here
}
} else {
$sql="SELECT * FROM `group` WHERE groupName <> 'admin' AND groupName <> 'poweruser'" ;
$result=mysql_query($sql,$connection);
//Output to let user select group.
echo("<h3>Groups</h3>");
while($line=mysql_fetch_array($result)){
echo "<a href='index.php?page=groups&group=".$line['groupID']."'>".$line['groupName'].'</a><br />';
}
}
mysql_free_result($result);
mysql_close($connection);
?>
if (isset($_GET["groupID"])) {
should that not be
if (isset($_GET["group"])) {
also change the $_GET["groupID"] to $_GET["group"] in ur $sql query
The following code is an example on how you could it. Just put it below the code you already have:
if ($_GET['page'] == 'groups'):
$groupID = $_GET['groupID'];
$sql = "SELECT * FROM users WHERE groupID = '$groupID'";
$res = mysql_query($sql); //MySQL query
$count = mysql_num_rows($res); //This counts our results
if($count != 0): //This makes sure we have at least 1 result
while($user = mysql_fetch_assoc($res)):
echo $user['name'];
endwhile;
endif;
endif;
Add Peter Stuart's code in your file and change
<a href='index.php?page ... > to <a href='groups.php?page ... >

Categories