PHP - Multiple Select queries based on If else conditions - php

I need help with Multiple Select queries based on If else conditions. I've multiple tables and I want to work queries like this.
Search in table1, if found then return the result.
If not found then search in table2.
If word not found in both table1 and table2 then check in table3 and after that check in table4
I'm using below codes.
<?php
// 1. Create a database connection
$mysqli = new mysqli("localhost", "root", "", "us");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = $mysqli->real_escape_string($term);
if($term=="") {
echo "Enter Something to search";
exit();
}
if(
$result = $mysqli->query("Select * from table1 where word like '{$term}%'
UNION
Select * from table2 where word like '{$term}%'")){
$num_rows = $result->num_rows;
if(mysqli_num_rows($result) >= 0) {
while($row = $result->fetch_assoc())
{
echo "Stem : {$row['word']} <br>";
}
}
else {
$result = $mysqli->query("Select * from table3 where words like '{$term}%'");
$num_rows = $result->num_rows;
if(mysqli_num_rows($result) >= 0) {
while($row = $result->fetch_assoc())
{
echo "words: {$row['words']} <br>";
}
}
}
}
else{
echo "No matches found!";
}
?>

try
str_replace($row['prefix'],'',$term );

<?php
mb_internal_encoding( 'UTF-8');
$mysqli = new mysqli("localhost", "root", "", "us");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("SET WORDS 'utf8'");
$mysqli->query('SET CHARACTER SET utf8');
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = $mysqli->real_escape_string($term);
if($term=="") {
echo "Enter Something to search";
exit();
}
termcheck($term, $mysqli);
function termcheck($term, $mysqli){
$qry="Select * from table1 where word ='$term' UNION Select * from table2 where word = '$term'";
if($result = $mysqli->query($qry)){
//echo "inside sql table1";
$num_rows = $result->num_rows;
if($num_rows > 0) {
//echo "inside table1";
while($row = $result->fetch_assoc())
{
echo "Stem : ".$row['term']."<br>";
}
exit();
}
}else {
$qry1="Select * from table3";
$result = $mysqli->query($qry1);
$num_rows = $result->num_rows;
if($num_rows > 0) {
while($row = $result->fetch_assoc()){
echo "inside while";
if($table4=mb_strrichr($term,$row['prefix'])){
echo "inside if";
$sterm=str_replace($row['prefix'],'',$term);
$postfix=$row['prefix'];
echo "inside : ".$sterm;
}
}
}else{echo "Error : Table3 doesn't exist";}
}
if(!empty($sterm)){
$qry3="Select * from table4";
$result3 = $mysqli->query($qry3);
$num_rows = $result3->num_rows;
if($num_rows > 0) {
while($row = $result3->fetch_assoc()){
if(mb_strrichr($sterm,$row['postfix'])){
$ssterm=str_replace($row['postfix'],'',$sterm);
$prefix=$row['postfix'];
echo "prefix : ".$prefix;
echo "<br>";
echo "postfix : ".$postfix;
echo "<br>";
echo "sterm : ".$ssterm;
}
}exit();
}else{echo "Error : Table3 doesn't exist";}
}else{
$qry3="Select * from table4";
$result3 = $mysqli->query($qry3);
$num_rows = $result3->num_rows;
if($num_rows > 0) {
while($row = $result3->fetch_assoc()){
if(mb_strrichr($term,$row['postfix'])){
$prefix=$row['postfix'];
$sterm=str_replace( $row['postfix'],'',$term);
echo "prefix : ".$prefix;
echo "<br>";
echo "sterm : ".$sterm;
}
}exit();
} else{echo "Error : Table3 doesn't exist";}
}
}
?>

Related

Mysql delete a row php

I have a MySQL table and i would like to delete a row in my table and after deleting the row the result must show all data left in my table .
<?php
include 'Connection.php';
// Create connection
$con= mysqli_connect($host,$user,$pass,$db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "SELECT * FROM productos";
$result = $con->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc())
{
$tem = $row;
$json = json_encode(array("productos"=>$tem));
}
} else {
echo "No Results Found.";
}
echo $json;
$con->close();
?>
This is my select code... now i don't know how create the delete function..
Any help please.
You are overwritting, make array of rows and then echo json_encode at last
$items = array();
if ($result->num_rows >0) {
while($row = $result->fetch_assoc())
{
$items[] = $row;
}
} else {
echo "No Results Found.";
}
echo json_encode(array("productos"=>$items));
$con->close();

php mysqli query if i add sum or count it doenst work

how do i count punten for each band_naw in php en so the result?
i have three dropdowns the first band you select is 3 punten second 2 punten and the third is 1 punten.
here is my code:
/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'root', '', 'popgroep');
$query = "SELECT band_naw, SUM(punten) AS punten FROM `resultaat` ";
$result = mysqli_query($dbConnection, $query);
if (mysqli_num_rows($result) > 0) {
echo "<ul>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<li>{$row['band_naw']} {$row['punten']}</li>";
}
echo "</ul>";
} else {
echo "Query didn't return any result";
}
my table
error said that column punten not exist but that its strange because i made it
thanks for the comments
If you want relative sumarization, you need to group your data with GROUP BY
SELECT band_naw, SUM(punten) AS punten FROM resultaat GROUP BY band_naw
Try this
$con = mysqli_connect("localhost", "root", "", "testing");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT band_naw, SUM(punten) AS punten FROM band GROUP BY band_naw";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0)
{
echo "<ul>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<li>".$row['band_naw']." ".$row['punten']."</li>";
}
echo "</ul>";
}
else
{
echo "No data found";
}

Conditional Logic on MySQL Query with PHP

I am doinga MySQL query to retreive data using PHP. I need to have a logic that if the data set returned is empty it shows a warning message else it displays the results:
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
mysqli_close($conn);
You need num_rows on the object
$result = mysqli_query($conn,$sql);
if ($result->num_rows == 0) {
echo 'result empty';
} else {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
http://php.net/manual/en/mysqli-result.num-rows.php
Change mysql_escape_string to mysqli_escape_string here
$where = "";
if(isset($_POST['searchQuery']) && trim($_POST['searchQuery'])){
$searchQuery = mysqli_escape_string($conn,$_POST['searchQuery']);
$where =" WHERE column1 = '".$searchQuery."'";
}
$sql="SELECT * FROM db.tblname ".$where;
It's as simple as this:
if ($result) {
//Your code
} else {
echo "Error: ".mysqli_error($conn);
}
First check with mysqli_num_rows(). Here is how to
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
else {
echo "No records found";
}
mysqli_close($conn);
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
} else {
echo "No results found";
}
mysqli_close($conn);

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

Getting two scripts to work together

I'm trying to use the following scripts so that the result of the first one determines the output of the second one.
<?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
?>
<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);
$query2 = "SELECT * FROM comments";
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2))
if ( $row2['commentid'] % 2 ==0 )
{
echo $row2['name'];
echo "<br />";
}
else
{
echo $row2['name'];
}
?>
So basically if the first script chooses Result 1 I only want to echo the names which associate with that result. The names are associated by commentid where an odd commentid would be result 2 and an even commentid would be result 1. Is there any way to do this without using a union statement?
It recommend that you to create a function and then call it.something like this :
<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach ($names as $name) {
echo $name . "<br/>";
}
}
else
{
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach ($names as $name) {
echo $name . "<br/>";
}
}
Function get_names($pool_result)
{
$name_array = array();
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
array_push($name_array , $row['name']);
}
return $name_array;
}
?>
}

Categories