I'm trying to select some rows from my database, and generate specific HTML where my selection finds something and other HTML when it does not.
This is my code. The problem is that it always finds no matches:
$pos = 0;
$con = mysqli_connect('localhost', 'user', 'pass', 'database');
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM table1 where user = 'user'")
or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result)) {
$result2 = mysqli_query($con,"SELECT * FROM table2 where id = '"
.$row['id']."'") or die("Error: ".mysqli_error($con));
$dbpos = $row['pos'];
while ($row2 = mysqli_fetch_array($result2)) {
if ($dbpos == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
$pos++;
}
}
mysqli_close($con);
I always get empty. What am I doing wrong?
Try making your query something like
Select * from table1
inner join table2
on table1.id=table2.id
Where table1.user='user'
This will do what you want in 1 query
If you get 1 result print found. If you get 0 then print empty
If you just want to determine if your query has an empty result or how many result was found, you can use mysqli_num_rows and remove your second while loop ($result2).
$noofrows=mysqli_num_rows($result2);
if($noofrows==0){
echo "Empty<br>";
}
else {
echo "There are ".$noofrows." record/s found.";
}
Try this. SQL joins can be very efficient depending on how your tables are structured.
//Query the DB for all of the rows in table2 where the table2 id column value
// is equal to the value of the id column value in table1
$query = "SELECT table2.*
FROM table1
INNER JOIN table2
ON table1.id = table2.id
WHERE table1.user = 'user'";
$result = mysqli_query($con, $query)or die(mysqli_error());
If you're expecting to return more than one row, the following might come in handy
$count = mysql_num_rows($result);
$i = 0;
while($row = mysqli_fetch_array($result)) {
$dbpos[$i] = $row['pos'];
$i++;
}
for($i=0;$i<$count;$i++) {
if($dbpos[$i] == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
}
If not, then simply do this
while($row = mysqli_fetch_array($result)) {
$dbpos = $row['pos'];
}
if($dbpos == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
More info about SQL joins here.
Related
I want to be able to select all rows where a value matches with the one I'm calling for in php
This is what I have for now and the only thing I get is the first row. Not the other rows.
<?php>
session_start();
require "db.inc.php";
$id = $_SESSION['userId'];
$sql = "SELECT followingId FROM following WHERE followerId=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
echo var_dump($result);
$followedId = $result['followingId'];
echo $followedId;
And $conn is the connection variable in db.inc.php
You must iterate through the results array you are fetching
while ($row = mysqli_fetch_array($result)) {
foreach($row as $field => $value) {
//do something with $field and $val
}
}
I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}
I trying to delete some data from three tables,
1:- ailments
2:- jnctn_ailments_symptoms
3:- symptoms
I tried to delete the Link first from Junction Table, Then Delete The Ailment (vise versa too) and then final check the symptoms for any other link with another ailment, if not delete the symptom from symptom table.
but I am failing at on step in foreach loop, I am checking the occurrences for symptoms beside the ailment deleted. everything is fine but when it comes to deleting the symptom I get mysql 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 '' at line 1".
I the ids for the symptoms are retrieved successfully but not delete query not working, somehow.
please see the following code and let me know where I am mistaken.
if(isset($_GET['del']))
{
$delID = $_GET['del'];
$originalSymptoms="";
$symptomO[] = array();
echo $delID;
$symp = "SELECT symptomID FROM symptoms
INNER JOIN jnctn_ailments_symptoms
ON jnctn_ailments_symptoms.FK_symptomID= symptoms.symptomID
INNER JOIN ailments
ON ailments.ailmentID = jnctn_ailments_symptoms.FK_ailmentID
WHERE ailments.ailmentID IN ('".$delID."')";
mysql_select_db($dbName);
$sympRes = mysql_query($symp,$con) or die(mysql_error());
while($symprow = mysql_fetch_assoc($sympRes))
{
if(empty($originalSymptoms))
{
$originalSymptoms = $symprow['symptomID'];
}
else
{
$originalSymptoms = $originalSymptoms.",".$symprow['symptomID'];
}
}
echo $originalSymptoms;
$newSymptoms = explode("," , $originalSymptoms);
foreach($newSymptoms as $symptom)
{
$originalSymptomsArray[] = $symptom;
}
echo count($originalSymptomsArray);
$delAilment = "DELETE FROM ailments WHERE ailmentID='$delID'";
$delAilmentResult = mysql_query($delAilment,$con) or die(mysql_error());
$delLink = "DELETE FROM jnctn_ailments_symptoms WHERE FK_ailmentID ='$delID'";
$delLinkResult = mysql_query($delLink,$con) or die(mysql_error());
foreach($originalSymptomsArray as $symptom)
{
echo $symptom."<br>";
$sql2 = "SELECT * FROM jnctn_ailments_symptoms WHERE FK_symptomID=".$symptom;
$result2 = mysql_query($sql2,$con);
$count = mysql_num_rows($result2);
if(!$result2 || $result2 != 0)
{
echo mysql_error();
$delSymptom = false;
}
else
{
$delSymptom = true;
}
if($delSymptom)
{
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='$symptom'";
$delResult = mysql_query($sqlDel,$con)or die(mysql_error());
if(!$delResult)
{
echo mysql_error();
}
else
{
echo "Symptoms Deleted!";
}
}
}
I have tried FK_symptomID='$symotom'"; , concatenation etc, nothing worked.
Try to concatenate all your queries mentioned as follows,
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='".$symptom."'";
somehow following code worked
foreach($originalSymptomsArray as $symptom)
{
$sql2 = "SELECT `ID`, `FK_ailmentID`, `FK_symptomID` FROM `jnctn_ailments_symptoms` WHERE `FK_symptomID`='".$symptom."'";
$result2 = mysql_query($sql2,$con);
$count = mysql_num_rows($result2);
if($count>0)
{
echo mysql_error();
$delSymptom = 0;
}
else
{
$delSymptom = 1;
}
if($delSymptom==1)
{
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='".$symptom."'";
$delResult = mysql_query($sqlDel,$con)or die(mysql_error());
if(!$delResult)
{
echo mysql_error();
}
}
}
thank you for concatenation suggestion, and thank you everybody.
i have query in my php code
$dbc = mysqli_connect('localhost', 'root','', 'delivery')
or die('Error connecting to MySQL server.');
$count = "SELECT MAX(id_pelanggan) FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$id_pelanggan = $result + 1;
}
and the result was
Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\delivery\addcustomer.php
whereas in mysql id_pelanggan datatype is int.
can anyone help me to make it works?
You try to assign your query to $id_pelanggan variable instead of the value from your query.
Fetch the result using *_fetch array() of your query
I've changed your if() condition because your $result won't be empty no matter what happens. The number of result maybe.
Put this and replace your if else condition:
if(mysqli_num_rows($result) == 0){ /* IF FOUND 0 RESULT */
$id_pelanggan = 1;
}
else {
while($row = mysqli_fetch_array($result)){
$maxid = $row["id_pelanggan"];
}
$id_pelanggan = $maxid + 1;
} /* END OF ELSE */
Simple fetch the result and increment it. You can do this by -
$count = "SELECT MAX(id_pelanggan) as max_id_pelanggan FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$data = mysqli_fetch_assoc($result);
$id_pelanggan = $data['max_id_pelanggan'] + 1;
}
if ($result = $db->query("SELECT * FROM tab WHERE ID = $id")) {
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
... }
$result->close();
} else {
echo "could not retrieve data from db"; }
I only get one result, but it should be a lot more.
How do I get all the results?
btw I cannot use fetch_all.
You are using an ID in your query, that means that you are asking for a specific item. In order to select all you have to remove this condition.
Your code would look like:
if ($result = $db->query("SELECT * FROM tab")) {
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
}
$result->close();
} else {
echo "There is no data in the database";
}
Replace
$result = $db->query("SELECT * FROM tab WHERE ID = $id"
with
$result = $db->query("SELECT * FROM tab WHERE ID = $id LIMIT 1"
You must select both id and product from tab and also add a where statement.
Your code would look like:
if ($result = $db->query("SELECT ID, Product, user FROM tab WHERE user='".$username."' ")) { //$username = john;
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
}
} else {
echo "There is no data in the database";
} result->close();
Let me hope your equate value is the name john it may be anything. so you will get all result rows from the database where the word john is listed.
put $username = 'john'; before the if statement.
The process of fetching data from a MYSQL result goes like this:
Connect to the host
Select the DB
Run the query
if ($result) //Check if the return is true
while($row = mysqli_fetch_array($result)) {
// do something with the $row
//like print it
}
}
In order to make fully sure print the query using
echo $your_query
Then run that query through phpMyAdmin and see what results or error you get.