Check if MySQL result is empty - php

I want to check if a MySQL result is empty and echo an error message.
This is my my current SQL-Script:
<?php
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_downloads WHERE gruppe = $gruppe_teilnehmer ORDER BY id DESC limit 4");
for($i=0;$i<$sql->getRows();$i++)
{
$id = $sql->getValue("id");
$dateiname = $sql->getValue("dateiname");
$dateigroesse = $sql->getValue("dateigroesse");
$dateipfad = $sql->getValue("dateipfad");
$dateidatum = date("d.m.Y",strtotime($sql->getValue("dateidatum")));
$dateizeit = date("H.i",strtotime($sql->getValue("dateidatum")));
$download_teilnehmer = $sql->getValue("teilnehmer");
$datei_projektnummer = $sql->getValue("projektnummer");
$projektseite = $sql->getValue("projektseite");
$ausgabe .= '<li><i class="fa fa-file-o"></i>'.$dateiname.'<ul><li><i class="fa fa-calendar"></i>'.$dateidatum.' | '.$dateizeit.'</li><li><i class="fa fa-circle"></i>'.$datei_projektnummer.'</li></ul></li>';
if(empty($ausgabe)) {
echo ("Error! No result!");
}
$sql->next();
}
?>
But there is no error message. I think the if-argument is wrong positioned.

Put it outside the loop:
<?php
$ausgabe = "";
$sql = new rex_sql;
$sql->debugsql = 0; //Ausgabe Query
$sql->setQuery("SELECT * FROM $db_downloads WHERE gruppe = $gruppe_teilnehmer ORDER BY id DESC limit 4");
for($i=0;$i<$sql->getRows();$i++)
{
$id = $sql->getValue("id");
$dateiname = $sql->getValue("dateiname");
$dateigroesse = $sql->getValue("dateigroesse");
$dateipfad = $sql->getValue("dateipfad");
$dateidatum = date("d.m.Y",strtotime($sql->getValue("dateidatum")));
$dateizeit = date("H.i",strtotime($sql->getValue("dateidatum")));
$download_teilnehmer = $sql->getValue("teilnehmer");
$datei_projektnummer = $sql->getValue("projektnummer");
$projektseite = $sql->getValue("projektseite");
$ausgabe .= '<li><i class="fa fa-file-o"></i>'.$dateiname.'<ul><li><i class="fa fa-calendar"></i>'.$dateidatum.' | '.$dateizeit.'</li><li><i class="fa fa-circle"></i>'.$datei_projektnummer.'</li></ul></li>';
$sql->next();
}
if(empty($ausgabe)) {
echo ("Error! No result!");
}
?>

Use php count function
if(!count($sql->getRows())) {
echo 'No data found';
}

Related

Trying to implement telegram api into this script New messages

how to implement this api telegram line into New messages? so it check and see if new messages, and then make the api call so i get a new message notification on my telegram bot
hope there is someone that know how to put this in : would be very usefull. i have tried but failed many attemps
this line:
$url = "https://api.telegram.org/bot6547564:AAGP6DH754460526544HCsvwTlfoGNJPaQ/sendMessage?chat_id=#841rhe67&text=Ny Besked på - Svar: https://fake.com/index.php?page=admin&p=sdeg";
file_get_contents($url);
into this
<?php
header('Content-Type: application/json');
require_once('../assets/includes/core.php');
function getFakeUsersChat($tab) {
global $mysqli,$sm;
$return = array();
$time_now = time()-300;
$timestamp = time();
$dw = date( "w", $timestamp);
if($tab == 'New'){
$query = $mysqli->query("SELECT DISTINCT s_id,r_id FROM chat where fake = 1 and online_day = '".$dw."' and seen = 0 order by id DESC");
} else {
$query = $mysqli->query("SELECT DISTINCT s_id,r_id FROM chat where fake = 1 and online_day = '".$dw."' order by id DESC");
}
$return['empty'] = false;
if ($query->num_rows > 0) {
while($value = $query->fetch_object()){
$senderName = getData('users','name','WHERE id ='.$value->s_id);
$fakeName = getData('users','name','WHERE id ='.$value->r_id);
$fakeId = $value->r_id;
$senderId = $value->s_id;
$fakePhoto = profilePhoto($value->r_id);
$senderStatus = userStatus($senderId);
$senderStatusIcon = 'avatar-online';
if($senderStatus == 'n'){
$senderStatusIcon = 'avatar-offline';
}
$chatId = getData('chat','id','WHERE s_id = '.$value->s_id.' AND r_id = '.$value->r_id.' ORDER BY id DESC LIMIT 1');
$searchName = strtolower($senderName);
$conv = $senderId.$fakeId;
$newMessagesFilter = 'WHERE r_id = '.$fakeId.' AND s_id = '.$senderId.' AND seen = 0';
$newMessagesCount = selectC('chat',$newMessagesFilter);
$return['conv'][] = $conv;
$return[$conv]['chatId'] = $chatId;
$newMessageLabel = '<span class="badge badge-pill badge-success" data-new-message="'.$chatId.'" style="margin-right:10px;font-size: 10px">NEW</span>';
if($tab == 'All'){
if($newMessagesCount == 0){
$newMessageLabel = '';
}
}
$return[$conv]['data'] = '<div class="list-group-item d-flex align-items-start border-right-3 border-right-primary bg-light rightSectionChatUser" data-conv="'.$conv.'" data-chatid="'.$chatId.'"
data-uid="'.$fakeId.'" data-search-bind="'.$searchName.'"
data-cid="'.$senderId.'" data-name="'.$fakeName.'" data-id="'.$fakeId.'" onclick="viewChat(this)" data-photo="'.profilePhoto($fakeId).'"
onmouseover="hoverFriendList(this,1)" onmouseout="hoverFriendList(this,2)" style="cursor: pointer;">
<div class="mr-3 d-flex flex-column align-items-center">
<div class="avatar avatar-md '.$senderStatusIcon.'" style="margin-bottom:5px" data-toggle="tooltip" data-placement="top" title="" data-original-title="'.$fakeName.'">
<img src="'.profilePhoto($senderId).'" alt="Avatar" class="avatar-img rounded-circle">
</div>
<div class="avatar avatar-md avatar-online" data-toggle="tooltip" data-placement="top" title="" data-original-title="'.$senderName.'">
<img src="'.profilePhoto($fakeId).'" alt="Avatar" class="avatar-img rounded-circle">
</div>
</div>
<div class="flex">
<p class="m-0">
<span class="d-flex align-items-center mb-1">
From: '.$senderName.'
<small class="ml-auto text-muted" style="font-size: 10px">
'.$newMessageLabel.'
'.getLastMessageMobileTime($fakeId,$senderId).'</small>
</span>
<span class="d-flex align-items-end">
<span class="flex mr-3">
<strong class="text-body mb-1">To: '.$fakeName.'</strong><br>
<small class="text-muted" style="margin-top:15px;max-height: 3rem; overflow: hidden; position: relative; display: inline-block;background: #fff;border-radius: 5px;padding: 5px 10px 5px 10px">
'.getLastMessageMobile($fakeId,$senderId).'
</small>
</span>
<a href="javascript:;" class="d-flex align-items-center mb-1">
<small class="text-muted mr-1">'.$newMessagesCount.'</small>
<i class="material-icons icon-16pt text-muted">chat</i>
</a>
</span>
</p>
</div>
</div>';
}
} else {
$return['empty'] = true;
}
return json_encode($return);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
switch ($_POST['action']) {
case 'load':
$uid = secureEncode($_POST['user']);
getUserInfo($uid,3);
$mysqli->query("UPDATE chat set seen = 1 where s_id = '".$sm['chat']['id']."' and r_id = '".$sm['user']['id']."'");
$arr =array();
$arr['id']=$sm['chat']['id'];
$arr['name']=$sm['chat']['name'];
$arr['chat'] = getChat($sm['user']['id'],$sm['chat']['id']);
echo json_encode($arr);
break;
case 'send':
global $mysqli;
if (strpos($_POST['message'], '<img') !== false) {
$message = mysqli_real_escape_string($mysqli, $_POST['message']);
} else {
$message = secureEncode($_POST['message']);
}
$r_id = secureEncode($_POST['r_id']);
$mobile = secureEncode($_POST['mobile']);
$time = time();
if(isset($_POST['fast'])){
$fast = secureEncode($_POST['fast']);
if($fast){
$date = date('m/d/Y', time());
$mysqli->query("INSERT INTO users_chat (uid,date,count,last_chat) VALUES ('".$sm['user']['id']."','".$date."',1,'".$time."') ON DUPLICATE KEY UPDATE count=count+1");
}
}
getUserInfo($r_id,1);
$fake = $sm['profile']['fake'];
$online_day = $sm['profile']['online_day'];
$data['message'] = $sm['lang'][658]['text'];
$data['chatHeaderRight']='<div class="js-message-block" id="you">
<div class="message">
<div class="brick brick--xsm brick--hover">
<div class="brick-img profile-photo" data-src="'.$sm['user']['profile_photo'].'"></div>
</div>
<div class="message__txt">
<span class="lgrey message__time" style="margin-right: 15px;">'.date("H:i", time()).'</span>
<div class="message__name lgrey">'.$sm['user']['first_name'].'</div>
<p class="montserrat chat-text">'.$message.'</p>
</div>
</div>
</div>
';
$data['time'] = date("H:i", time());
$event = 'chat'.$r_id.$sm['user']['id'];
$noti= 'notification'.$r_id;
$data['id'] = $sm['user']['id'];
$data['type'] = 1;
$data['icon'] = $sm['user']['profile_photo'];
$data['name'] = $sm['user']['first_name'];
$data['photo'] = 0;
$data['action'] = 'message';
$sm['push']->trigger($sm['plugins']['pusher']['key'], $event, $data);
$mysqli->query("INSERT INTO chat (s_id,r_id,time,message,fake,online_day) VALUES ('".$sm['user']['id']."','".$r_id."','".$time."','".$message."','".$fake."','".$online_day."')");
$arr = array();
$data['notification_chat'] = false;
$results = $mysqli->query("SELECT DISTINCT s_id FROM chat WHERE r_id = '".$r_id."' AND seen = 0 AND notification = 0 order by id desc");
if($results->num_rows > 0){
$data['notification_chat'] = getUserFriends($r_id);
$data['unread'] = checkUnreadMessages($r_id);
}
$sm['push']->trigger($sm['plugins']['pusher']['key'], $noti, $data);
if($fake == 0){
$sm['profile_notifications'] = userNotifications($sm['profile']['id']);
if($sm['profile']['last_access']+300 <= time() && $sm['profile_notifications']['message'] == 1){
chatMailNotification($r_id,$message);
}
}
$arr['message'] = cleanMessage($message);
if($mobile == 1){
$arr['chat'] = getLastChatMobile($sm['user']['id'],$r_id);
} else {
$arr['chat'] = getLastChat($sm['user']['id'],$r_id);
}
//activity content
if($sm['plugins']['logActivity']['enabled'] == 'Yes'){
$ac = array();
$ac['u1']['id'] = $sm['user']['id'];
$ac['u2']['id'] = $sm['profile']['id'];
$ac['u1']['name'] = $sm['user']['first_name'];
$ac['u2']['name'] = $sm['profile']['first_name'];
$ac['u1']['photo'] = $sm['user']['profile_photo'];
$ac['u2']['photo'] = $sm['profile']['profile_photo'];
$ac['message'] = $arr['message'];
$adminPush= 'adminActivity';
$pushData['message'] = $ac;
$ac = json_encode($ac);
$title = $sm['user']['first_name'].' sent a message to '.$sm['profile']['first_name'];
activity('message',$ac,$title);
$sm['push']->trigger($sm['plugins']['pusher']['key'], $adminPush, $pushData);
}
break;
case 'send_fake':
$message = secureEncode($_POST['mensaje']);
$r_id = secureEncode($_POST['uid2']);
$s_id = secureEncode($_POST['uid1']);
$mobile = secureEncode($_POST['mobile']);
$time = time();
getUserInfo($r_id,1);
$fake = $sm['profile']['fake'];
getUserInfo($s_id,6);
$data['message'] = cleanMessage($message);
if($mobile == 1){
$data['chat'] = getLastChatMobile($sm['search']['id'],$r_id);
} else {
$data['chatHeaderRight']='<div class="js-message-block" id="you">
<div class="message">
<div class="brick brick--xsm brick--hover">
<div class="brick-img profile-photo" data-src="'.$sm['search']['profile_photo'].'"></div>
</div>
<div class="message__txt">
<span class="lgrey message__time" style="margin-right: 15px;">'.date("H:i", $spotl->time).'</span>
<div class="message__name lgrey">'.$sm['search']['first_name'].'</div>
<p class="montserrat chat-text">'.cleanMessage($message).'</p>
</div>
</div>
</div>
';
}
$data['time'] = date("H:i", time());
$event = 'chat'.$r_id.$sm['search']['id'];
$noti= 'notification'.$r_id;
$data['id'] = $sm['search']['id'];
$data['type'] = 1;
$data['icon'] = $sm['search']['profile_photo'];
$data['name'] = $sm['search']['first_name'];
$data['photo'] = 0;
$mysqli->query("INSERT INTO chat (s_id,r_id,time,message,fake) VALUES ('".$s_id."','".$r_id."','".$time."','".$message."','".$fake."')");
$arr = array();
$data['notification_chat'] = false;
$results = $mysqli->query("SELECT DISTINCT s_id FROM chat WHERE r_id = '".$r_id."' AND seen = 0 AND notification = 0 order by id desc");
if($results->num_rows > 0){
$data['notification_chat'] = getUserFriends($r_id);
$data['unread'] = checkUnreadMessages($r_id);
}
$sm['push']->trigger(siteConfig('pusher_key'), $event, $data);
$sm['push']->trigger(siteConfig('pusher_key'), $noti, $data);
if($fake == 0){
$sm['profile_notifications'] = userNotifications($sm['profile']['id']);
if($sm['profile']['last_access']+300 >= time() && $sm['profile_notifications']['message'] == 1){
chatMailNotification($r_id,$message);
}
}
$arr['message'] = cleanMessage($message);
if($mobile == 1){
$arr['chat'] = getLastChatMobile($s_id,$r_id);
} else {
$arr['chat'] = getLastChat($s_id,$r_id);
}
echo json_encode($arr);
break;
case 'fake_list':
$tab = secureEncode($_POST['tab']);
echo getFakeUsersChat($tab);
break;
case 'load_fake':
$u1 = secureEncode($_POST['u1']);
$u2 = secureEncode($_POST['u2']);
//Secure info
$u1 = secureEncode($u1);
$u2 = secureEncode($u2);
//Get all chats
$chatt = $mysqli->query("SELECT * FROM chat where s_id = '".$u1."' and r_id = '".$u2."' OR r_id = '".$u1."' and s_id = '".$u2."' order by id asc");
//Update chat to seen
$mysqli->query("UPDATE chat set seen = 1 where s_id = '".$u2."' and r_id = '".$u1."'");
if ($chatt->num_rows > 0) {
while($chat= $chatt->fetch_object()){
//Get profile photo
$mensaje = $chat->message;
//Check if current user is the sender
if($chat->s_id == $u1){
if($chat->seen == 1){
echo'
<li class="me">
<div class="image">
<img src="'.profilePhoto($chat->s_id).'"/>
</div>
<p> '.$mensaje.' </p>
</li>
';
} else {
echo'
<li class="me">
<div class="image">
<img src="'.profilePhoto($chat->s_id).'"/>
</div>
<p> '.$mensaje.' </p>
</li>
';
}
} else {
echo'
<li class="you">
<div class="image">
<img src="'.profilePhoto($chat->s_id).'"/>
</div>
<p> '.$mensaje.' </p>
</li>
';
}
}
}
break;
case 'current_fake':
//GET POST INFO
$u1 = secureEncode($_POST['u1']);
$u2 = secureEncode($_POST['u2']);
//GET NEW MESSAGES
$results = $mysqli->query("SELECT * FROM chat WHERE r_id = '".$u1."' AND s_id = '".$u2."' AND seen = 0 order by id asc");
//CHECK IF CURRENT USER HAS NEW MESSAGE
if($results->num_rows > 0){
while ($obj = $results->fetch_object()){
//UPDATE MESSAGE AS SEEN
$mysqli->query("UPDATE chat SET seen = 1 where r_id = '".$u1."' and s_id = '".$u2."'");
//SHOW NEW MESSAGES
echo'
<li class="you">
<div class="image">
<img src="'.profilePhoto($obj->s_id).'"/>
</div>
<p> '.$obj->message.' </p>
</li>
';
}
}
break;
case 'access':
$time = time();
$access = secureEncode($_POST['access']);
$r_id = secureEncode($_POST['r_id']);
if($access == 1) {
$mysqli->query("INSERT INTO chat (s_id,r_id,time,message) VALUES
('".$sm['user']['id']."','".$r_id."','".$time."','".$sm['lang'][189]['text']."')");
$mysqli->query("UPDATE chat SET access = 2 WHERE s_id = '".$r_id."' AND r_id = '".$sm['user']['id']."' AND access = 1");
$mysqli->query("INSERT INTO blocked_photos (u1,u2) VALUES ('".$r_id."','".$sm['user']['id']."')");
} else {
$mysqli->query("INSERT INTO chat (s_id,r_id,time,message) VALUES
('".$sm['user']['id']."','".$r_id."','".$time."','".$sm['lang'][190]['text']."')");
$mysqli->query("UPDATE chat SET access = 2 WHERE s_id = '".$r_id."' AND r_id = '".$sm['user']['id']."' AND access = 1");
}
break;
case 'current':
$uid = secureEncode($_POST['uid']);
$mob = secureEncode($_POST['mobile']);
getUserInfo($uid,3);
$arr = array();
$arr['result'] = 0;
$results = $mysqli->query("SELECT s_id,id,photo FROM chat WHERE r_id = '".$sm['user']['id']."' AND s_id = '".$uid."' AND seen = 0 order by id asc");
if($results->num_rows > 0){
$re = $results->fetch_object();
$arr['result'] = 1;
$arr['photo'] = $re->photo;
if($mob == 1){
$arr['chat'] = getLastChatMobile2($sm['user']['id'],$uid);
} else {
$arr['chat'] = getLastMessage($sm['user']['id'],$uid);
}
$arr['message'] = cleanMessageById($re->id);
$mysqli->query("UPDATE chat set seen = 1 where r_id = '".$sm['user']['id']."' and s_id = '".$uid."'");
}
echo json_encode($arr);
break;
case 'read':
$id = secureEncode($_POST['id']);
$mysqli->query("UPDATE chat set seen = 1, notification = 1 where r_id = '".$sm['user']['id']."' and s_id = '".$id."'");
break;
case 'notification':
$user = secureEncode($_POST['user']);
$time = time();
$arr = array();
if($user == 0){
$results = $mysqli->query("SELECT DISTINCT s_id FROM chat WHERE r_id = '".$sm['user']['id']."' AND seen = 0 AND notification = 0 order by id desc");
} else {
$results = $mysqli->query("SELECT DISTINCT s_id FROM chat WHERE r_id = '".$sm['user']['id']."' AND s_id <> '".$user."' AND seen = 0 AND notification = 0 order by id desc");
}
if($results->num_rows > 0){
while($use = $results->fetch_object()){
$arr[] = $use->s_id;
}
$mysqli->query("UPDATE chat set notification = 1 where r_id = '".$sm['user']['id']."'");
}
echo json_encode($arr);
break;
case 'new':
echo getUserFriends($sm['user']['id']);
break;
case 'today':
$uid = secureEncode($sm['user']['id']);
$time = time();
$date = date('m/d/Y', time());
$mysqli->query("INSERT INTO users_chat (uid,date,count,last_chat) VALUES ('".$uid."','".$date."',1,'".$time."') ON DUPLICATE KEY UPDATE count=count+1");
break;
case 'chat_limit':
$uid = secureEncode($sm['user']['id']);
$date = date('m/d/Y', time());
$mysqli->query("DELETE FROM users_chat WHERE uid = '".$uid."' AND date = '".$date."'");
break;
}
}
//CLOSE DB CONNECTION
$mysqli->close();

Select query php sql injection

I'm doing a test on a code that I had previously written, my goal is to write safer queries but I don't understand why it doesn't work
working query:
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query_string = "SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = 0
AND richieste.inviata = 'SI'
AND richieste.token_inserito = 'NO'
AND richieste.richiesta_scaduta = 'NO'
AND richieste.categoria_richiesta = '$categoria_professionista'
AND richieste.scadenza_richiesta >= '$oggi'
";
$query_richieste_disponibili = mysqli_query($connessione, $query_string);
<?php while($row = mysqli_fetch_assoc($query_richieste_disponibili)){ ?>
......
<?php } ?>
query not working:
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query = $connessione->prepare("
SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = ?
AND richieste.inviata = ?
AND richieste.token_inserito = ?
AND richieste.richiesta_scaduta = ?
AND richieste.categoria_richiesta = ?
AND richieste.scadenza_richiesta >= ?");
$query->bind_param('isssii', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
$query_richieste_disponibili = $query->execute();
<?php while($row = mysqli_fetch_assoc($query_richieste_disponibili)){ ?>
......
<?php } ?>
as I repeat my intent is to write queries against sql injection and therefore safer
edit for #Barmar
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query = $connessione->prepare("
SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = ?
AND richieste.inviata = ?
AND richieste.token_inserito = ?
AND richieste.richiesta_scaduta = ?
AND richieste.categoria_richiesta = ?
AND richieste.scadenza_richiesta >= ?");
$query->bind_param('isssii', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
$query_richieste_disponibili = $query->execute();
<?php
if ($query->execute()) {
$query_richieste_disponibili = $query->get_result();
while($row = $query_richieste_disponibili->fetch_assoc()) { ?>
<?php }
} ?>
I followed your code that you kindly wrote together with the explanation but when I report it it doesn't work, where am I wrong?
$query->execute() doesn't return a result object, it returns TRUE or FALSE. You need to call $query->get_result to get a result that you can fetch rows from.
And since $oggi is a string, you need the s type in bind_param().
$query->bind_param('isssis', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
if ($query->execute()) {
$query_richieste_disponibili = $query->get_result();
while($row = $query_richieste_disponibili->fetch_assoc()) { ?>
......
<?php }
}
Note that it only works this way if you use the mysqlnd driver. If not, you have to use $query->bind_result() and $query->fetch().

Inverting order of exhibition of the elements in PHP

I want to invert the order of these elements when they are exhibited on my menu:
function buscarSubCateg($categ_id) {
global $con;
$buscar_subcateg = "SELECT * FROM subcateg WHERE categ_id = '$categ_id'";
$run_subcateg = mysqli_query($con, $buscar_subcateg);
$i=0;
while ($row_subcateg = mysqli_fetch_array($run_subcateg)) {
$subcateg_id = $row_subcateg['subcateg_id'];
$subcateg_name = $row_subcateg['subcateg_name'];
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>'.buscarTipos($subcateg_id);
$i++;
}
}
function buscarTipos($subcateg_id) {
global $con;
$buscar_tipo = "SELECT * FROM tipoprod WHERE subcateg_id = '$subcateg_id'";
$run_tipo = mysqli_query($con, $buscar_tipo);
while ($row_tipo = mysqli_fetch_array($run_tipo)) {
$tipo_id = $row_tipo['tipoprod_id'];
$tipo_name = $row_tipo['tipoprod_name'];
echo "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
}
}
In this echo:
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>'.buscarTipos($subcateg_id);`
I want that the function buscarTipos()'s result be shown after $subcateg_name. The way it is now is doing the opposite, first showing buscarTipos()'s result and after shwoing $subcateg_name.
Thanks.
Replace your current code with the following:
function buscarSubCateg($categ_id) {
global $con;
$buscar_subcateg = "SELECT * FROM subcateg WHERE categ_id = '$categ_id'";
$run_subcateg = mysqli_query($con, $buscar_subcateg);
$i=0;
while ($row_subcateg = mysqli_fetch_array($run_subcateg)) {
$subcateg_id = $row_subcateg['subcateg_id'];
$subcateg_name = $row_subcateg['subcateg_name'];
$tip = buscarTipos($subcateg_id);
echo $tip;
echo '<div class="sectionSub"><a class="linkSubCatergoria" href="#">'.$subcateg_name.'</a></div>';
$i++;
}
}
function buscarTipos($subcateg_id) {
global $con;
$buscar_tipo = "SELECT * FROM tipoprod WHERE subcateg_id = '$subcateg_id'";
$run_tipo = mysqli_query($con, $buscar_tipo);
$str = '';
while ($row_tipo = mysqli_fetch_array($run_tipo)) {
$tipo_id = $row_tipo['tipoprod_id'];
$tipo_name = $row_tipo['tipoprod_name'];
$str = $str."<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
}
return $str;
}
Try changing line #34
echo "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
into
return "<div class='sectionTipo'><a class='linkTipo' href='#'>$tipo_name</a></div>";
Then the calling function will echo sectionSub before echoing sectionTipo
Or change your SQL to
$sql = 'select a.categ_id, a.subcateg_id, b.tipoprod_id, b.tipoprod_name
from subcateg as a, tipoprod as b where categ_id='$categ_id'
and a.subcateg_id = b.subcateg_id';
and lose the secondary function completely. That gets MySQL to do the join between your two tables and is an order of magnitude easier to work with.

delete not working properly in while loop

here i am trying to delete from detail table here is one problem with my code if detail table have three records than only delete one record from detail table.and also it does not effect other two records in stock table..
Only one first record this code work properly after that it does not work in for delete query from detail table and not effected in stock table...
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0) {
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId, colorId,
totalkg, purchaseDetailId, partyId
FROM purchasedetail
JOIN purchasemaster ON
purchaseMaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster);
while($purRow = mysql_fetch_array($selectMasterRes)) {
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes)) {
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes) {
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes){
$deleteMst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$deleteMstRes = mysql_query($deleteMst) or die(mysql_error());
if(!$deleteMstRes) {
echo "Purchase Master Delete Fail";
} else {
header("Location:purdetail.php");
exit();
}
}
}
}
}
?>
Here is my updated code with perfect code working
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0)
{
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId,colorId,totalkg,purchaseDetailId,partyId
FROM purchasedetail
JOIN purchasemaster ON purchasemaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster) or die(mysql_error());
while($purRow = mysql_fetch_array($selectMasterRes))
{
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes))
{
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes)
{
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes)
{
$selectid = "SELECT purchaseDetailId
FROM purchasedetail
WHERE purchaseMasterId = ".$purchaseMasterId;
$selectidRes = mysql_query($selectid);
if(mysql_affected_rows() == 0)
{
$mst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$purchaseMasterId;
$mstRes = mysql_query($mst) or die(mysql_error());;
if($mstRes)
{
header("Location:purdetail.php");
exit();
}
else
{
}
}
}
}
}
}
?>

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories