Multiple if else in mysql query - php

I have re-written this question because of all the down votes and it would seem that either no one understood the question or was unwilling to help a newbie. So I'll as it this way: Can someone tell/show me why this code does not work? (500 error)
OR... at the very least point me in the right direction? I AM WILLING TO LEARN, I just don't know where to begin or who/where to learn from as I am not sure what to even ask other than how do you run multiple "else" statements... that however left me more confused than I already am though!
Any "HELP" would be greatly appreciated!
<?php
$servername = "localhost";
$username = "****";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$bname = $_POST['bname'];
$baddress = $_POST['baddress'];
$bcity = $_POST['bcity'];
$bstate = $_POST['bstate'];
$zipcode = $_POST['zipcode'];
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Login FROM `USERS` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/realsite.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "SELECT Login FROM `DATA` WHERE Business_Name = '" . $_POST["bname"] . "' AND Business_Address = '" . $_POST["baddress"] . "' AND Business_State = '" . $_POST["bstate"] . "' AND Business_Zip = '" . $_POST["zipcode"] . "' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
echo "https://www.***.com/demo.php?Login=" . $row["Login"] . "";
}
}
else
{
$sql = "INSERT INTO `DATA` (Business_Name, Business_Address, Business_City, Business_State, Business_Zip)
SELECT '$bname', '$baddress', '$bcity', '$bstate', '$zipcode' FROM (SELECT 1) t
WHERE NOT EXISTS (SELECT Login, Business_Name,Business_Address FROM `DATA` WHERE Business_Name='$bname' AND Business_Address='$baddress')";
if (mysqli_query($conn, $sql))
{
echo "<a href='https://www.servedwell.com/realsite.php?Login=" . $row["Login"] . "'>LINK</a>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
}
?>

Credit goes to #Ancaron for properly formatting code and correcting a syntax error. Final posted code works fine.

Related

Problem getting results with php and mysqli

I've a problem by running this php script:
<?php
$link = mysqli_connect("localhost", "root", "*******", "adsb");
/* check connection */
if ($conn->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$query = "SELECT aircrafts.id, heli.reg, heli.hex, heli.typ, heli.opp, aircrafts.flight, aircrafts.altitude, aircrafts.lat, aircrafts.lon, aircrafts.squawk, aircrafts.message_date FROM `aircrafts` JOIN `heli` ON aircrafts.hex=heli.hex WHERE aircrafts.id='2414';";
$query .= "SELECT aircrafts.id, plane.reg, plane.hex, plane.typ, plane.opp, aircrafts.flight, aircrafts.altitude, aircrafts.lat, aircrafts.lon, aircrafts.squawk, aircrafts.message_date FROM `aircrafts` JOIN `plane` ON aircrafts.hex=plane.hex WHERE aircrafts.id='2414'";
$result = mysqli_multi_query($query);
/* execute multi query */
if ($result->num_rows > 0) {
echo "<h1>INFO ABOUT FLIGHT RECORD " . $id . "</h1>";
echo "<table><th>Registratie</th><th>ICAO24</th><th>Type</th><th>Operator</th><th>Callsign</th><th>Squawk</th><th>Time</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td><a href='aircraft.php?hex=" . $row["hex"] . "'>" . $row["reg"] . "</a></td><td>" . $row["hex"] . "</td><td><img src='/database/SilhouttesLogos/" . $row["typ"] . ".bmp' /></td><td><img src='/database/OperatorFlags/" . $row["opp"] . ".bmp' /></td><td>" . $row["flight"] . "</td><td>" . $row["squawk"] . "</td><td>" . $row["message_date"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
/* close connection */
mysqli_close($link);
When I run the 2 query's in phpmyadmin I get 1 result.
(When I run 1 query on my site I get a result too, see code at the bottom of this post)
But when I run it on my site it's shows "0 results".
So... There must be a fould in the $result section.
Who can help? :-)
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "adsb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT aircrafts.id, heli.reg, heli.hex, heli.typ, heli.opp, aircrafts.flight, aircrafts.altitude, aircrafts.lat, aircrafts.lon, aircrafts.squawk, aircrafts.message_date FROM `aircrafts` JOIN `heli` ON aircrafts.hex=heli.hex WHERE aircrafts.id=2414";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><th>Registratie</th><th>ICAO24</th><th>Type</th><th>Operator</th><th>Callsign</th><th>Squawk</th><th>Time</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td><a href='aircraft.php?hex=" . $row["hex"] . "'>" . $row["reg"] . "</a></td><td>" . $row["hex"] . "</td><td><img src='/database/SilhouttesLogos/" . $row["typ"] . ".bmp' /></td><td><img src='/database/OperatorFlags/" . $row["opp"] . ".bmp' /></td><td>" . $row["flight"] . "</td><td>" . $row["squawk"] . "</td><td>" . $row["message_date"] . "</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
This is probably your specific problem.
$result = mysqli_multi_query($query);
Here is the PHP Doc
You need to establish the connection.
$result = mysqli_multi_query($link, $query);
Like the others mentioned in the comments, I would refactor this code.

Get all rows from MySQL Query

The PHP Code:
<?php
//Server Information
$servername = "localhost";
$dbusername = "USERNAME";
$password = "TOTALLYSECUREPASSWORD";
$dbname = "DEFINITELYADATABASE";
//Query Information
$guid = $_POST['GUID'];
$username = $_POST['USERNAME'];
$admin_username = $_POST['ADMIN_USERNAME'];
$ban_reason = $_POST['BAN_REASON'];
$ip = $_POST['IP'];
//Create Connection
$connection = mysqli_connect($servername, $dbusername, $password, $dbname);
//Check the Connection
if ($connection->connect_error){
die("Connection failed: " . $connection->connect_error);
}
//$sql = "SELECT DATE, DBUSERNAME, GUID, IP, USERNAME, BAN_REASON FROM bans";
//$result = $connection->query($sql);
$sql = "SELECT * FROM bans WHERE";
$types = json_decode($_POST['QUERY_TYPE'], true);
if (in_array("query_admin_username", $types)) {
$sql = $sql . " DBUSERNAME = " . "\"" . $admin_username . "\"" . " &&";
}
if (in_array("query_guid", $types)) {
$sql = $sql . " GUID = " . "\"". $guid . "\"" . " &&";
}
if (in_array("query_ip", $types)) {
$sql = $sql . " IP = " . "\"" . $ip . "\"" . " &&";
}
if (in_array("query_username", $types)) {
$sql = $sql . " USERNAME = " . "\"" . $username . "\"" . " &&";
}
if (in_array("query_ban_reason", $types)) {
$sql = $sql . " BAN_REASON = " . "\"" . $ban_reason . "\"" . " &&";
}
$sql_query = substr($sql, 0, -3);
echo ($sql_query);
$result = $connection->query($sql_query);
while ($connection->query($sql_query)) {
}
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$row = $result->fetch_array(MYSQLI_NUM);
while ($row = mysqli_fetch_assoc($result)) {
echo ($row);
}
mysqli_close($connection);
?>
As weird as all that looks, it works just how I want it to (I think).
My issue:
I want to be able to get the data from each row and export it as one large String, something along the lines of:
[DATE] DBUSERNAME banned USERNAME (GUID / IP) for BAN_REASON.
I just have absolutely no idea how to go about this. I've tested the Query and it's returning everything it should, however I was using "echo ($row[0])" etc to display them, which is pretty impractical if it's going to return a large amount of rows.
Sorry if something doesn't make sense, my brain is fried at the moment. Please let me know if I forgot anything.
You could concatenate the columns like this if the rest of your script works:
SELECT CONCAT('[',DATE,'] ',DBUSERNAME,' banned ',USERNAME,'(',COALESCE(GUID, IP),),') for ', BAN_REASON) AS your_columns_in_one_line FROM your_table WHERE .....;
See this link for reference to CONCAT

Can not check the duplicate data in database using PHP,Mysql and Angular.js

i am finding little bit difficult to check duplicate data from database using MYsql,PHP and angular.js.I am explaining my code below.
addUser.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_email=$request->user_email;
$mob_no=$request->mob_no;
$login_name=$request->login_name;
$password=$request->password;
$user_status=$request->user_status;
$con = mysql_connect('localhost', 'root', 'Oditek123#');
mysql_select_db('go_fasto', $con);
$selquery = "SELECT * FROM db_user WHERE login_name='".$login_name."' and mob_no='".$mob_no."' and email='" . $user_email . "'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0)
{
$erresult=mysql_fetch_array($selres);
header("HTTP/1.0 401 Unauthorized");
$erresult['msg'] = 'This user login name or mobile no or email is already exist.';
}else{
$qry ='INSERT INTO db_user (user_name,email,mob_no,login_name,password,user_status) values ("' . $user_name . '","' . $user_email . '","' . $mob_no . '","' .$login_name . '","' . $password . '","' . $user_status . '")';
$qry_res = mysql_query($qry);
$user_type = 5;
$display_name = $user_name."_admin";
$qry ='INSERT INTO db_Admin_Master (user_type,user_name,display_name,password) values ("' . $user_type . '","' . $login_name . '","' . $display_name . '","' .$password . '")';
$qry_res = mysql_query($qry);
$query='SELECT * from db_user order by user_id desc';
$res=mysql_query($query);
$result=mysql_fetch_array($res);
if ($result) {
$result['msg'] = "New User has added successfully";
} else {
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = "Sorry, User could not added ";
}
echo json_encode($result);
}
?>
If you will check my code i am checking three column such as login_name,email and mob_no from database and checking it inside if statement.Here even if i am inserting the same data again it is not checking and else part is executing.Please help me to resolve this issue.
$selquery = "SELECT *
FROM db_user
WHERE login_name='".$login_name."'
OR mob_no='".$mob_no."'
OR email='" . $user_email . "'";
use OR instead of AND try

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

Why am I getting white spaces from this function?

I made a function that loops through all the posts in database and echo them. But there's a slight problem. I am getting whitespace between the name (title of the post) and the content, its like two lines or so. I want reason for this and solution. Thanks.
function read_all_posts(){
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'website';
$con = mysqli_connect($host, $username, $password, $database);
$query = "SELECT * FROM posts";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<br>" . $row['content'] . "<br />" . "<i>" . $row['author'] . "</i>";
echo "<br>";
}
}
try,
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<p>" . $row['content'] . "</p>" . "<p><i>" . $row['author'] . "</i></p>";
}

Categories