Ir para conteúdo

Pesquisar na Comunidade

Mostrando resultados para as tags ''MYsql''.

  • Pesquisar por Tags

    Digite tags separadas por vírgulas
  • Pesquisar por Autor

Tipo de Conteúdo


Todas as áreas do Fórum

  • Q&A Desenvolvimento
    • Perguntas e respostas rápidas
  • Desenvolvimento Web
    • Desenvolvimento frontend
    • Javascript
    • PHP
    • Ruby
    • Python
    • Java
    • .NET
    • Docker, Kubernets e outros ambientes
    • Desenvolvimento com Wordpress
    • Desenvolvimento de apps
    • Desenvolvimento ágil
    • Desenvolvimento de Games
    • Banco de Dados
    • Design e UX
    • Algoritmos & Outras Tecnologias
  • Entretenimento e uso pessoal
    • Segurança & Malwares
    • Geral
    • Boteco iMasters

Encontrar resultados em...

Encontrar resultados que...


Data de Criação

  • Início

    FIM


Data de Atualização

  • Início

    FIM


Filtrar pelo número de...

Data de Registro

  • Início

    FIM


Grupo


Google+


Hangouts


Skype


Twitter


deviantART


Github


Flickr


LinkedIn


Pinterest


Facebook


Site Pessoal


Localização


Interesses

Encontrado 617 registros

  1. Rodrigo5468

    Mostrar Resultados sem Repetir Dados

    Olá a todos(as), boa tarde! Tenho uma Query e um pequeno código em PHP para mostrar os resultados em uma tabela, mas estão repetindo os resultados da Query. Gostaria de uma solução, ou uma gambiarra para isso. Query SELECT DISTINCT b.ID AS "ID", b.Character AS "Personagem", b.Money AS "DinMao", b.BankMoney AS "DinBanco", b.Savings2 AS "DinPoupa", c.houseOwner AS "IDono", SUM(c.houseMoney) AS "DinCasa" FROM characters b INNER JOIN houses c ON (b.ID = c.houseOwner) ORDER BY ((b.Money+b.BankMoney+b.Savings2+c.houseMoney)) DESC LIMIT 0, 1000 PHP if(mysqli_num_rows($q) > 0) { while($r = $q->fetch_assoc()) { //Código da Tabela } } Observação: Quando eu removo a seguinte parte da minha Query que é: SUM(c.houseMoney) AS "DinCasa" e deixo assim: c.houseMoney AS "DinCasa" Os dados da minha tabela repetem, não sei o motivo e/ou a circunstância disso. Mas peço a ajuda de vocês para solucionar. Vale ressaltar que (ID e houseOwner) tem os mesmos valores, só o valor da casa que recebe o valor do ID, e ele pode ter quantas casa ele quiser, e se ele tiver cinco casas, mostrará o resultado cinco resultados na minha tabela, como posso resolver isso? Meu muito obrigado desde já.
  2. guilhermefdavid

    Quais extensões ativar para funções PHP funcionarem?

    Olá, tenho uma aplicação PHP com algumas funções que não estão funcionando na hospedagem. Esta aplicação utiliza apenas conexão com banco de dados -> mysql_connect, mysql_select_db, entre outras de MYSQL. Alguma ideia de qual extensão, dentre as existentes na imagem anexa deveria(m) estar ativada(s)? Um abraço!
  3. Rafaellaranjo

    Alto consumo de CPU

    Estou sofrendo a um tempo com consumo alto de CPU em meu servidor na maioria dos casos em virtude do MYSQL, trabalho com PHP e APACHE e MYSQL. Realizei inúmeras tentativas para acabar com o alto consumo porém todas fracassadas. O evento costuma ocorrer sempre nos mesmos horários, parte da manhã por volta de 9:30/11:00 e parte da tarde entre 14:00/16:00. Meu servidor possui hardware suficiente para suportar, porem acredito que esteja mal configurado. Estou encaminhando alguns processos que observo estar executando em excesso obtidos através do ps aux. dovecot/pop3-login dovecot/imap-login dovecot/lmtp -L php-fpm: pool app (o que mais aparece) Ps: utilizo um servidor CENTOS 7
  4. user32

    problema com action

    Boa tarde pessoal, acredito que estou com o problema e a solução no post só que nao sei exatamente aonde alterar o codigo. Um site de servidor de games de um cliente esta com um problema na aba forum. é um forum simples para questoes relacionadas ao game. Irei anexar alguns prints para facilitar o entendimento e o codigo. Resumindo: O problema é que o forum tem algumas boards (News, Wars, Quests, Pictures e Bug reports), suponhamos que dessas boards Pictures tem 4 posts e Quests 1 post. Se o primeito post do forum for em Pictures, quando eu tentar abrir o post de Quests ele ira me redirecionar para Pictures, e dentro de pictures terá todos os posts de todas as boards. Se eu tentar excluir algum topico de qualquer board, todos os topicos são excluidos. Acredito que o problema esteja no criação do ID do post na database, todos estão sendo gerados como ID 0. Imagino que a função new_post não está trabalhando corretamente. se alguem puder me ajudar eu fico muito agradecido mesmo!! to quebrando a cabeça aqui a um tempo, só falta isso pra terminar. PRINTS E EXPLICAÇÃO: print de todos as boards print da board war (observe que existe apenas um post nessa board) print apos selecionar post da board war (repare que fui redirecionado para a board Report Bug que foi a que eu criei o primeiro post do forum como expliquei acima no resumo) print do banco de dados (todos os IDs são 0) <?php if(!defined('INITIALIZED')) exit; // CONFIG $level_limit = 30; // minimum 1 character with 30 lvl on account to post $post_interval = 20; // 20 seconds between posts $group_not_blocked = $config['site']['access_admin_panel']; // group id of player that can always post, remove post, remove threads $posts_per_page = 20; $threads_per_page = 20; // SECTION WITH ID 1 IS FOR "NEWS", ONLY ADMINS CAN CREATE NEW THREAD IN IT $sections = array(1 => 'News', 2 => 'Wars', 3 => 'Quests', 4 => 'Pictures', 5 => 'Bug Report'); $sections_desc = array(1 => 'Here you can comment news.', 2 => 'Feel free to tell what you think about your enemy.', 3 => 'Talk with others about quests you made and how to make them.', 4 => 'Show others your best photos from server!', 5 => 'Report bugs on website and in-game here.'); // END function canPost($account) { if($account->isLoaded()) if(!$account->isBanned()) { $SQL = $GLOBALS['SQL']; $level_limit = $GLOBALS['level_limit']; $player = $SQL->query("SELECT " . $SQL->fieldName('level') . " FROM " . $SQL->tableName('players') . " WHERE " . $SQL->fieldName('account_id') . " = ".$SQL->quote($account->getId())." ORDER BY " . $SQL->fieldName('level') . " DESC")->fetch(); if($player['level'] >= $level_limit) return true; } return false; } function replaceSmile($text, $smile) { $smileys = array(';D' => 1, ':D' => 1, ':cool:' => 2, ';cool;' => 2, ':ekk:' => 3, ';ekk;' => 3, ';o' => 4, ';O' => 4, ':o' => 4, ':O' => 4, ':(' => 5, ';(' => 5, ':mad:' => 6, ';mad;' => 6, ';rolleyes;' => 7, ':rolleyes:' => 7, ':)' => 8, ';d' => 9, ':d' => 9, ';)' => 10); if($smile == 1) return $text; else { foreach($smileys as $search => $replace) $text = str_replace($search, '<img src="images/forum/smile/'.$replace.'.gif" />', $text); return $text; } } function replaceAll($text, $smile) { $rows = 0; while(stripos($text, '[code]') !== false && stripos($text, '[/code]') !== false && stripos($text, '[code]') < stripos($text, '[/code]')) { $code = substr($text, stripos($text, '[code]')+6, stripos($text, '[/code]') - stripos($text, '[code]') - 6); if(!is_int($rows / 2)) { $bgcolor = 'ABED25'; } else { $bgcolor = '23ED25'; } $rows++; $text = str_ireplace('[code]'.$code.'[/code]', '<i>Code:</i><br /><table cellpadding="0" style="background-color: #'.$bgcolor.'; width: 480px; border-style: dotted; border-color: #CCCCCC; border-width: 2px"><tr><td>'.$code.'</td></tr></table>', $text); } $rows = 0; while(stripos($text, '[quote]') !== false && stripos($text, '[/quote]') !== false && stripos($text, '[quote]') < stripos($text, '[/quote]')) { $quote = substr($text, stripos($text, '[quote]')+7, stripos($text, '[/quote]') - stripos($text, '[quote]') - 7); if(!is_int($rows / 2)) { $bgcolor = 'AAAAAA'; } else { $bgcolor = 'CCCCCC'; } $rows++; $text = str_ireplace('[quote]'.$quote.'[/quote]', '<table cellpadding="0" style="background-color: #'.$bgcolor.'; width: 480px; border-style: dotted; border-color: #007900; border-width: 2px"><tr><td>'.$quote.'</td></tr></table>', $text); } $rows = 0; while(stripos($text, '[url]') !== false && stripos($text, '[/url]') !== false && stripos($text, '[url]') < stripos($text, '[/url]')) { $url = substr($text, stripos($text, '[url]')+5, stripos($text, '[/url]') - stripos($text, '[url]') - 5); $text = str_ireplace('[url]'.$url.'[/url]', '<a href="'.$url.'" target="_blank">'.$url.'</a>', $text); } while(stripos($text, '[player]') !== false && stripos($text, '[/player]') !== false && stripos($text, '[player]') < stripos($text, '[/player]')) { $player = substr($text, stripos($text, '[player]')+8, stripos($text, '[/player]') - stripos($text, '[player]') - 8); $text = str_ireplace('[player]'.$player.'[/player]', '<a href="?subtopic=characters&name='.urlencode($player).'">'.$player.'</a>', $text); } while(stripos($text, '[img]') !== false && stripos($text, '[/img]') !== false && stripos($text, '[img]') < stripos($text, '[/img]')) { $img = substr($text, stripos($text, '[img]')+5, stripos($text, '[/img]') - stripos($text, '[img]') - 5); $text = str_ireplace('[img]'.$img.'[/img]', '<img src="'.$img.'">', $text); } while(stripos($text, '[b]') !== false && stripos($text, '[/b]') !== false && stripos($text, '[b]') < stripos($text, '[/b]')) { $b = substr($text, stripos($text, '[b]')+3, stripos($text, '[/b]') - stripos($text, '[b]') - 3); $text = str_ireplace('[b]'.$b.'[/b]', '<b>'.$b.'</b>', $text); } while(stripos($text, '[i]') !== false && stripos($text, '[/i]') !== false && stripos($text, '[i]') < stripos($text, '[/i]')) { $i = substr($text, stripos($text, '[i]')+3, stripos($text, '[/i]') - stripos($text, '[i]') - 3); $text = str_ireplace('[i]'.$i.'[/i]', '<i>'.$i.'</i>', $text); } while(stripos($text, '[u]') !== false && stripos($text, '[/u]') !== false && stripos($text, '[u]') < stripos($text, '[/u]')) { $u = substr($text, stripos($text, '[u]')+3, stripos($text, '[/u]') - stripos($text, '[u]') - 3); $text = str_ireplace('[u]'.$u.'[/u]', '<u>'.$u.'</u>', $text); } return replaceSmile($text, $smile); } function removeBBCode($text) { while(stripos($text, '[code]') !== false && stripos($text, '[/code]') !== false ) { $code = substr($text, stripos($text, '[code]')+6, stripos($text, '[/code]') - stripos($text, '[code]') - 6); $text = str_ireplace('[code]'.$code.'[/code]', $code, $text); } while(stripos($text, '[quote]') !== false && stripos($text, '[/quote]') !== false ) { $quote = substr($text, stripos($text, '[quote]')+7, stripos($text, '[/quote]') - stripos($text, '[quote]') - 7); $text = str_ireplace('[quote]'.$quote.'[/quote]', $quote, $text); } while(stripos($text, '[url]') !== false && stripos($text, '[/url]') !== false ) { $url = substr($text, stripos($text, '[url]')+5, stripos($text, '[/url]') - stripos($text, '[url]') - 5); $text = str_ireplace('[url]'.$url.'[/url]', $url, $text); } while(stripos($text, '[player]') !== false && stripos($text, '[/player]') !== false ) { $player = substr($text, stripos($text, '[player]')+8, stripos($text, '[/player]') - stripos($text, '[player]') - 8); $text = str_ireplace('[player]'.$player.'[/player]', $player, $text); } while(stripos($text, '[img]') !== false && stripos($text, '[/img]') !== false ) { $img = substr($text, stripos($text, '[img]')+5, stripos($text, '[/img]') - stripos($text, '[img]') - 5); $text = str_ireplace('[img]'.$img.'[/img]', $img, $text); } while(stripos($text, '[b]') !== false && stripos($text, '[/b]') !== false ) { $b = substr($text, stripos($text, '[b]')+3, stripos($text, '[/b]') - stripos($text, '[b]') - 3); $text = str_ireplace('[b]'.$b.'[/b]', $b, $text); } while(stripos($text, '[i]') !== false && stripos($text, '[/i]') !== false ) { $i = substr($text, stripos($text, '[i]')+3, stripos($text, '[/i]') - stripos($text, '[i]') - 3); $text = str_ireplace('[i]'.$i.'[/i]', $i, $text); } while(stripos($text, '[u]') !== false && stripos($text, '[/u]') !== false ) { $u = substr($text, stripos($text, '[u]')+3, stripos($text, '[/u]') - stripos($text, '[u]') - 3); $text = str_ireplace('[u]'.$u.'[/u]', $u, $text); } return $text; } function codeLower($text) { return str_ireplace(array('[b]', '[i]', '[u]', '[/u][/i][/b][i][u]', '[/u][/i][u]', '[/u]', '[url]', '[player]', '[img]', '[code]', '[quote]', '[/quote][/code][/url][code][quote]', '[/player]', '[/img]', '[/quote][/code][quote]', '[/quote]'), array('[b]', '[i]', '[u]', '[/u][/i][/b][i][u]', '[/u][/i][u]', '[/u]', '[url]', '[player]', '[img]', '[code]', '[quote]', '[/quote][/code][/url][code][quote]', '[/player]', '[/img]', '[/quote][/code][quote]', '[/quote]'), $text); } function showPost($topic, $text, $smile) { $text = nl2br($text); $post = ''; if(!empty($topic)) $post .= '<b>'.replaceSmile($topic, $smile).'</b><hr />'; $post .= replaceAll($text, $smile); return $post; } if(!$logged) $main_content .= 'You are not logged in. <a href="?subtopic=accountmanagement">Log in</a> to post on the forum.<br /><br />'; if($action == '') { $main_content .= '<b>Boards</b>'; $main_content .= '<table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'"><td><font color="white" size="1"><b>Board</b></font></td><td><font color="white" size="1"><b>Posts</b></font></td><td><font color="white" size="1"><b>Threads</b></font></td><td align="center"><font color="white" size="1"><b>Last Post</b></font></td></tr>'; $info = $SQL->query("SELECT " . $SQL->fieldName('section') . ", COUNT(" . $SQL->fieldName('id') . ") AS 'threads', SUM(" . $SQL->fieldName('replies') . ") AS 'replies' FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->fieldName('first_post') . " = " . $SQL->fieldName('id') . " GROUP BY " . $SQL->fieldName('section') . "")->fetchAll(); foreach($info as $data) $counters[$data['section']] = array('threads' => $data['threads'], 'posts' => $data['replies'] + $data['threads']); foreach($sections as $id => $section) { $last_post = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " = ".(int) $id." AND " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " ORDER BY " . $SQL->fieldName('post_date') . " DESC LIMIT 1")->fetch(); if(!is_int($number_of_rows / 2)) { $bgcolor = $config['site']['darkborder']; } else { $bgcolor = $config['site']['lightborder']; } $number_of_rows++; $main_content .= '<tr bgcolor="'.$bgcolor.'"><td><a href="?subtopic=forum&action=show_board&id='.$id.'">'.$section.'</a><br /><small>'.$sections_desc[$id].'</small></td><td>'.(int) $counters[$id]['posts'].'</td><td>'.(int) $counters[$id]['threads'].'</td><td>'; if(isset($last_post['name'])) $main_content .= date('d.m.y H:i:s', $last_post['post_date']).'<br />by <a href="?subtopic=characters&name='.urlencode($last_post['name']).'">'.$last_post['name'].'</a>'; else $main_content .= 'No posts'; $main_content .= '</td></tr>'; } $main_content .= '</table>'; } if($action == 'show_board') { $section_id = (int) $_REQUEST['id']; $page = (int) $_REQUEST['page']; $threads_count = $SQL->query("SELECT COUNT(" . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ") AS threads_count FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " = ".(int) $section_id." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . "")->fetch(); for($i = 0; $i < $threads_count['threads_count'] / $threads_per_page; $i++) { if($i != $page) $links_to_pages .= '<a href="?subtopic=forum&action=show_board&id='.$section_id.'&page='.$i.'">'.($i + 1).'</a> '; else $links_to_pages .= '<b>'.($i + 1).' </b>'; } $main_content .= '<a href="?subtopic=forum">Boards</a> >> <b>'.$sections[$section_id].'</b><br /><br /><a href="?subtopic=forum&action=new_topic&section_id='.$section_id.'"><img src="images/forum/topic.gif" border="0" /></a><br /><br />Page: '.$links_to_pages.'<br />'; $last_threads = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('last_post') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('replies') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('views') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " = ".(int) $section_id." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " ORDER BY " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('last_post') . " DESC LIMIT ".$threads_per_page." OFFSET ".($page * $threads_per_page))->fetchAll(); if(isset($last_threads[0])) { $main_content .= '<table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'" align="center"><td><font color="white" size="1"><b>Thread</b></font></td><td><font color="white" size="1"><b>Thread Starter</b></font></td><td><font color="white" size="1"><b>Replies</b></font></td><td><font color="white" size="1"><b>Views</b></font></td><td><font color="white" size="1"><b>Last Post</b></font></td></tr>'; foreach($last_threads as $thread) { if(!is_int($number_of_rows / 2)) { $bgcolor = $config['site']['darkborder']; } else { $bgcolor = $config['site']['lightborder']; } $number_of_rows++; $main_content .= '<tr bgcolor="'.$bgcolor.'"><td>'; if($logged && $group_id_of_acc_logged >= $group_not_blocked) $main_content .= '<a href="?subtopic=forum&action=remove_post&id='.$thread['id'].'" onclick="return confirm(\'Are you sure you want remove thread > '.htmlspecialchars($thread['post_topic']).' <?\')"><font color="red">[REMOVE]</font></a> '; $main_content .= '<a href="?subtopic=forum&action=show_thread&id='.$thread['id'].'">'.htmlspecialchars($thread['post_topic']).'</a><br /><small>'.htmlspecialchars(substr(removeBBCode($thread['post_text']), 0, 50)).'...</small></td><td><a href="?subtopic=characters&name='.urlencode($thread['name']).'">'.$thread['name'].'</a></td><td>'.(int) $thread['replies'].'</td><td>'.(int) $thread['views'].'</td><td>'; if($thread['last_post'] > 0) { $last_post = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread['id']." AND " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " ORDER BY " . $SQL->fieldName('post_date') . " DESC LIMIT 1")->fetch(); if(isset($last_post['name'])) $main_content .= date('d.m.y H:i:s', $last_post['post_date']).'<br />by <a href="?subtopic=characters&name='.urlencode($last_post['name']).'">'.$last_post['name'].'</a>'; else $main_content .= 'No posts.'; } else $main_content .= date('d.m.y H:i:s', $thread['post_date']).'<br />by <a href="?subtopic=characters&name='.urlencode($thread['name']).'">'.$thread['name'].'</a>'; $main_content .= '</td></tr>'; } $main_content .= '</table><br /><a href="?subtopic=forum&action=new_topic&section_id='.$section_id.'"><img src="images/forum/topic.gif" border="0" /></a>'; } else $main_content .= '<h3>No threads in this board.</h3>'; } if($action == 'show_thread') { $thread_id = (int) $_REQUEST['id']; $page = (int) $_REQUEST['page']; $thread_name = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread_id." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " AND " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " LIMIT 1")->fetch(); if(!empty($thread_name['name'])) { $posts_count = $SQL->query("SELECT COUNT(" . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ") AS posts_count FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread_id)->fetch(); for($i = 0; $i < $posts_count['posts_count'] / $threads_per_page; $i++) { if($i != $page) $links_to_pages .= '<a href="?subtopic=forum&action=show_thread&id='.$thread_id.'&page='.$i.'">'.($i + 1).'</a> '; else $links_to_pages .= '<b>'.($i + 1).' </b>'; } $threads = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('account_id') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('world_id') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('rank_id') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('vocation') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('promotion') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('level') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . "," . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . "," . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_smile') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_aid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('last_edit_aid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('edit_date') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread_id." ORDER BY " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " LIMIT ".$posts_per_page." OFFSET ".($page * $posts_per_page))->fetchAll(); if(isset($threads[0]['name'])) $SQL->query("UPDATE " . $SQL->tableName('z_forum') . " SET " . $SQL->fieldName('views') . "=" . $SQL->fieldName('views') . "+1 WHERE " . $SQL->fieldName('id') . " = ".(int) $thread_id); $main_content .= '<a href="?subtopic=forum">Boards</a> >> <a href="?subtopic=forum&action=show_board&id='.$threads[0]['section'].'">'.$sections[$threads[0]['section']].'</a> >> <b>'.htmlspecialchars($thread_name['post_topic']).'</b>'; $main_content .= '<br /><br /><a href="?subtopic=forum&action=new_post&thread_id='.$thread_id.'"><img src="images/forum/post.gif" border="0" /></a><br /><br />Page: '.$links_to_pages.'<br /><table width="100%"><tr bgcolor="'.$config['site']['lightborder'].'" width="100%"><td colspan="2"><font size="4"><b>'.htmlspecialchars($thread_name['post_topic']).'</b></font><font size="1"><br />by <a href="?subtopic=characters&name='.urlencode($thread_name['name']).'">'.htmlspecialchars($thread_name['name']).'</a></font></td></tr><tr bgcolor="'.$config['site']['vdarkborder'].'"><td width="200"><font color="white" size="1"><b>Author</b></font></td><td>&nbsp;</td></tr>'; foreach($threads as $thread) { if(!is_int($number_of_rows / 2)) { $bgcolor = $config['site']['darkborder']; } else { $bgcolor = $config['site']['lightborder']; } $number_of_rows++; $main_content .= '<tr bgcolor="'.$bgcolor.'"><td valign="top"><a href="?subtopic=characters&name='.urlencode($thread['name']).'">'.htmlspecialchars($thread['name']).'</a><br /><br /><font size="1">Profession: '.htmlspecialchars(Website::getVocationName($thread['vocation'], $thread['promotion'])).'<br />Level: '.$thread['level'].'<br />'; $rank = new GuildRank($thread['rank_id']); if($rank->isLoaded()) { $guild = $rank->getGuild(); if($guild->isLoaded()) $main_content .= htmlspecialchars($rank->getName()).' of <a href="?subtopic=guilds&action=show&guild='.$guild->getId().'">'.htmlspecialchars($guild->getName()).'</a><br />'; } $posts = $SQL->query("SELECT COUNT(" . $SQL->fieldName('id') . ") AS 'posts' FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->fieldName('author_aid') . "=".(int) $thread['account_id'])->fetch(); $main_content .= '<br />Posts: '.(int) $posts['posts'].'<br /></font></td><td valign="top">'.showPost(htmlspecialchars($thread['post_topic']), htmlspecialchars($thread['post_text']), $thread['post_smile']).'</td></tr> <tr bgcolor="'.$bgcolor.'"><td><font size="1">'.date('d.m.y H:i:s', $thread['post_date']); if($thread['edit_date'] > 0) { if($thread['last_edit_aid'] != $thread['author_aid']) $main_content .= '<br />Edited by moderator'; else $main_content .= '<br />Edited by '.htmlspecialchars($thread['name']); $main_content .= '<br />on '.date('d.m.y H:i:s', $thread['edit_date']); } $main_content .= '</font></td><td>'; if($logged && $group_id_of_acc_logged >= $group_not_blocked) if($thread['first_post'] != $thread['id']) $main_content .= '<a href="?subtopic=forum&action=remove_post&id='.$thread['id'].'" onclick="return confirm(\'Are you sure you want remove post of '.htmlspecialchars($thread['name']).'?\')"><font color="red">REMOVE POST</font></a>'; else $main_content .= '<a href="?subtopic=forum&action=remove_post&id='.$thread['id'].'" onclick="return confirm(\'Are you sure you want remove thread > '.htmlspecialchars($thread['post_topic']).' <?\')"><font color="red">REMOVE THREAD</font></a>'; if($logged && ($thread['account_id'] == $account_logged->getId() || $group_id_of_acc_logged >= $group_not_blocked)) $main_content .= '<br/><a href="?subtopic=forum&action=edit_post&id='.$thread['id'].'">EDIT POST</a>'; if($logged) $main_content .= '<br/><a href="?subtopic=forum&action=new_post&thread_id='.$thread_id.'&quote='.$thread['id'].'">Quote</a>'; $main_content .= '</td></tr>'; } $main_content .= '</table><br /><a href="?subtopic=forum&action=new_post&thread_id='.$thread_id.'"><img src="images/forum/post.gif" border="0" /></a><br /><center>Pages:<br />'.$links_to_pages.'<br /></center>'; } else $main_content .= 'Thread with this ID does not exits.'; } if($action == 'remove_post') { if($logged && $group_id_of_acc_logged >= $group_not_blocked) { $id = (int) $_REQUEST['id']; $post = $SQL->query("SELECT " . $SQL->fieldName('id') . ", " . $SQL->fieldName('first_post') . ", " . $SQL->fieldName('section') . " FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->fieldName('id') . " = ".$id." LIMIT 1")->fetch(); if($post['id'] == $id) { if($post['id'] == $post['first_post']) { $SQL->query("DELETE FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->fieldName('first_post') . " = ".$post['id']); header('Location: ?subtopic=forum&action=show_board&id='.$post['section']); } else { $post_page = $SQL->query("SELECT COUNT(" . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ") AS posts_count FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " < ".$id." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $post['first_post'])->fetch(); $page = (int) ceil($post_page['posts_count'] / $threads_per_page) - 1; $SQL->query("UPDATE " . $SQL->tableName('z_forum') . " SET " . $SQL->fieldName('replies') . " = " . $SQL->fieldName('replies') . " - 1 WHERE " . $SQL->fieldName('id') . " = ".$post['first_post']); $SQL->query("DELETE FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->fieldName('id') . " = ".$post['id']); header('Location: ?subtopic=forum&action=show_thread&id='.$post['first_post'].'&page='.(int) $page); } } else $main_content .= 'Post with ID '.$id.' does not exist.'; } else $main_content .= 'You are not logged in or you are not moderator.'; } if($action == 'new_post') { if($logged) { if(canPost($account_logged) || $group_id_of_acc_logged >= $group_not_blocked) { $players_from_account = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " FROM " . $SQL->tableName('players') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('account_id') . " = ".(int) $account_logged->getId())->fetchAll(); $thread_id = (int) $_REQUEST['thread_id']; $thread = $SQL->query("SELECT " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " = ".(int) $thread_id." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread_id." LIMIT 1")->fetch(); $main_content .= '<a href="?subtopic=forum">Boards</a> >> <a href="?subtopic=forum&action=show_board&id='.$thread['section'].'">'.$sections[$thread['section']].'</a> >> <a href="?subtopic=forum&action=show_thread&id='.$thread_id.'">'.htmlspecialchars($thread['post_topic']).'</a> >> <b>Post new reply</b><br /><h3>'.htmlspecialchars($thread['post_topic']).'</h3>'; if(isset($thread['id'])) { $quote = (int) $_REQUEST['quote']; $text = trim(codeLower($_REQUEST['text'])); $char_id = (int) $_REQUEST['char_id']; $post_topic = trim($_REQUEST['topic']); $smile = (int) $_REQUEST['smile']; $saved = false; if(isset($_REQUEST['quote'])) { $quoted_post = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " = ".(int) $quote)->fetchAll(); if(isset($quoted_post[0]['name'])) $text = '[i]Originally posted by '.$quoted_post[0]['name'].' on '.date('d.m.y H:i:s', $quoted_post[0]['post_date']).':[/i][quote]'.$quoted_post[0]['post_text'].'[/quote]'; } elseif(isset($_REQUEST['save'])) { $lenght = 0; for($i = 0; $i <= strlen($text); $i++) { if(ord($text[$i]) >= 33 && ord($text[$i]) <= 126) $lenght++; } if($lenght < 1 || strlen($text) > 15000) $errors[] = 'Too short or too long post (short: '.$lenght.' long: '.strlen($text).' letters). Minimum 1 letter, maximum 15000 letters.'; if($char_id == 0) $errors[] = 'Please select a character.'; $player_on_account == false; if(count($errors) == 0) { foreach($players_from_account as $player) if($char_id == $player['id']) $player_on_account = true; if(!$player_on_account) $errors[] = 'Player with selected ID '.$char_id.' doesn\'t exist or isn\'t on your account'; } if(count($errors) == 0) { $last_post = $account_logged->getCustomField('last_post'); if($last_post+$post_interval-time() > 0 && $group_id_of_acc_logged < $group_not_blocked) $errors[] = 'You can post one time per '.$post_interval.' seconds. Next post after '.($last_post+$post_interval-time()).' second(s).'; } if(count($errors) == 0) { $saved = true; $account_logged->set('last_post', time()); $account_logged->save(); $SQL->query("INSERT INTO " . $SQL->tableName('z_forum') . " (" . $SQL->fieldName('first_post') . " ," . $SQL->fieldName('last_post') . " ," . $SQL->fieldName('section') . " ," . $SQL->fieldName('replies') . " ," . $SQL->fieldName('views') . " ," . $SQL->fieldName('author_aid') . " ," . $SQL->fieldName('author_guid') . " ," . $SQL->fieldName('post_text') . " ," . $SQL->fieldName('post_topic') . " ," . $SQL->fieldName('post_smile') . " ," . $SQL->fieldName('post_date') . " ," . $SQL->fieldName('last_edit_aid') . " ," . $SQL->fieldName('edit_date') . ", " . $SQL->fieldName('post_ip') . ") VALUES ('".$thread['id']."', '0', '".$thread['section']."', '0', '0', '".$account_logged->getId()."', '".(int) $char_id."', ".$SQL->quote($text).", ".$SQL->quote($post_topic).", '".(int) $smile."', '".time()."', '0', '0', '".$_SERVER['REMOTE_ADDR']."')"); $SQL->query("UPDATE " . $SQL->tableName('z_forum') . " SET " . $SQL->fieldName('replies') . "=" . $SQL->fieldName('replies') . "+1, " . $SQL->fieldName('last_post') . "=".time()." WHERE " . $SQL->fieldName('id') . " = ".(int) $thread_id); $post_page = $SQL->query("SELECT COUNT(" . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ") AS posts_count FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " <= ".time()." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread['id'])->fetch(); $page = (int) ceil($post_page['posts_count'] / $threads_per_page) - 1; header('Location: ?subtopic=forum&action=show_thread&id='.$thread_id.'&page='.$page); $main_content .= '<br />Thank you for posting.<br /><a href="?subtopic=forum&action=show_thread&id='.$thread_id.'">GO BACK TO LAST THREAD</a>'; } } if(!$saved) { if(count($errors) > 0) { $main_content .= '<font color="red" size="2"><b>Errors occured:</b>'; foreach($errors as $error) $main_content .= '<br />* '.$error; $main_content .= '</font><br />'; } $main_content .= '<form action="?" method="POST"><input type="hidden" name="action" value="new_post" /><input type="hidden" name="thread_id" value="'.$thread_id.'" /><input type="hidden" name="subtopic" value="forum" /><input type="hidden" name="save" value="save" /><table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'"><td colspan="2"><font color="white"><b>Post New Reply</b></font></td></tr><tr bgcolor="'.$config['site']['darkborder'].'"><td width="180"><b>Character:</b></td><td><select name="char_id"><option value="0">(Choose character)</option>'; foreach($players_from_account as $player) { $main_content .= '<option value="'.$player['id'].'"'; if($player['id'] == $char_id) $main_content .= ' selected="selected"'; $main_content .= '>'.$player['name'].'</option>'; } $main_content .= '</select></td></tr><tr bgcolor="'.$config['site']['lightborder'].'"><td><b>Topic:</b></td><td><input type="text" name="topic" value="'.htmlspecialchars($post_topic).'" size="40" maxlength="60" /> (Optional)</td></tr> <tr bgcolor="'.$config['site']['darkborder'].'"><td valign="top"><b>Message:</b><font size="1"><br />You can use:<br />[player]Nick[/player]<br />[url=http://address.com/]Address Search - Find Email and Addresses @ Address.com[/url]<br />[img=http://images.com/images3.gif]<br />[code]Code[/code]<br />[b]<b>Text</b>[/b]<br />[i]<i>Text</i>[/i]<br />[u]<u>Text</u>[/u]<br />and smileys:<br />;) , :) , :D , :( , :rolleyes:<br />:cool: , :eek: , :o , :p</font></td><td><textarea rows="10" cols="60" name="text">'.htmlspecialchars($text).'</textarea><br />(Max. 15,000 letters)</td></tr> <tr bgcolor="'.$config['site']['lightborder'].'"><td valign="top">Options:</td><td><label><input type="checkbox" name="smile" value="1"'; if($smile == 1) $main_content .= ' checked="checked"'; $main_content .= '/>Disable Smileys in This Post </label></td></tr></table><center><input type="submit" value="Post Reply" /></center></form>'; $threads = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_smile') . " FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread_id." ORDER BY " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " DESC LIMIT 10")->fetchAll(); $main_content .= '<table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'"><td colspan="2"><font color="white"><b>Last 5 posts from thread: '.htmlspecialchars($thread['post_topic']).'</b></font></td></tr>'; foreach($threads as $thread) { if(is_int($number_of_rows / 2)) { $bgcolor = $config['site']['darkborder']; } else { $bgcolor = $config['site']['lightborder']; } $number_of_rows++; $main_content .= '<tr bgcolor="'.$bgcolor.'"><td>'.$thread['name'].'</td><td>'.showPost(htmlspecialchars($thread['post_topic']), htmlspecialchars($thread['post_text']), $thread['post_smile']).'</td></tr>'; } $main_content .= '</table>'; } } else $main_content .= 'Thread with ID '.$thread_id.' doesn\'t exist.'; } else $main_content .= 'Your account is banned, deleted or you don\'t have any player with level '.$level_limit.' on your account. You can\'t post.'; } else $main_content .= 'Login first.'; } if($action == 'edit_post') { if($logged) { if(canPost($account_logged) || $group_id_of_acc_logged >= $group_not_blocked) { $post_id = (int) $_REQUEST['id']; $thread = $SQL->query("SELECT " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_aid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_smile') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " = ".(int) $post_id." LIMIT 1")->fetch(); if(isset($thread['id'])) { $first_post = $SQL->query("SELECT " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_aid') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_topic') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_text') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_smile') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ", " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('section') . " FROM " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . " = ".(int) $thread['first_post']." LIMIT 1")->fetch(); $main_content .= '<a href="?subtopic=forum">Boards</a> >> <a href="?subtopic=forum&action=show_board&id='.$thread['section'].'">'.$sections[$thread['section']].'</a> >> <a href="?subtopic=forum&action=show_thread&id='.$thread['first_post'].'">'.htmlspecialchars($first_post['post_topic']).'</a> >> <b>Edit post</b>'; if($account_logged->getId() == $thread['author_aid'] || $group_id_of_acc_logged >= $group_not_blocked) { $players_from_account = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " FROM " . $SQL->tableName('players') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('account_id') . " = ".(int) $account_logged->getId())->fetchAll(); $saved = false; if(isset($_REQUEST['save'])) { $text = trim(codeLower($_REQUEST['text'])); $char_id = (int) $_REQUEST['char_id']; $post_topic = trim($_REQUEST['topic']); $smile = (int) $_REQUEST['smile']; $lenght = 0; for($i = 0; $i <= strlen($post_topic); $i++) { if(ord($post_topic[$i]) >= 33 && ord($post_topic[$i]) <= 126) $lenght++; } if(($lenght < 1 || strlen($post_topic) > 60) && $thread['id'] == $thread['first_post']) $errors[] = 'Too short or too long topic (short: '.$lenght.' long: '.strlen($post_topic).' letters). Minimum 1 letter, maximum 60 letters.'; $lenght = 0; for($i = 0; $i <= strlen($text); $i++) { if(ord($text[$i]) >= 33 && ord($text[$i]) <= 126) $lenght++; } if($lenght < 1 || strlen($text) > 15000) $errors[] = 'Too short or too long post (short: '.$lenght.' long: '.strlen($text).' letters). Minimum 1 letter, maximum 15000 letters.'; if($char_id == 0) $errors[] = 'Please select a character.'; if(empty($post_topic) && $thread['id'] == $thread['first_post']) $errors[] = 'Thread topic can\'t be empty.'; $player_on_account == false; if(count($errors) == 0) { foreach($players_from_account as $player) if($char_id == $player['id']) $player_on_account = true; if(!$player_on_account) $errors[] = 'Player with selected ID '.$char_id.' doesn\'t exist or isn\'t on your account'; } if(count($errors) == 0) { $saved = true; if($account_logged->getId() != $thread['author_aid']) $char_id = $thread['author_guid']; $SQL->query("UPDATE " . $SQL->tableName('z_forum') . " SET " . $SQL->fieldName('author_guid') . " = ".(int) $char_id.", " . $SQL->fieldName('post_text') . " = ".$SQL->quote($text).", " . $SQL->fieldName('post_topic') . " = ".$SQL->quote($post_topic).", " . $SQL->fieldName('post_smile') . " = ".(int) $smile.", " . $SQL->fieldName('last_edit_aid') . " = ".(int) $account_logged->getId()."," . $SQL->fieldName('edit_date') . " = ".time()." WHERE " . $SQL->fieldName('id') . " = ".(int) $thread['id']); $post_page = $SQL->query("SELECT COUNT(" . $SQL->tableName('z_forum') . "." . $SQL->fieldName('id') . ") AS posts_count FROM " . $SQL->tableName('players') . ", " . $SQL->tableName('z_forum') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " = " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('author_guid') . " AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('post_date') . " <= ".$thread['post_date']." AND " . $SQL->tableName('z_forum') . "." . $SQL->fieldName('first_post') . " = ".(int) $thread['first_post'])->fetch(); $page = (int) ceil($post_page['posts_count'] / $threads_per_page) - 1; header('Location: ?subtopic=forum&action=show_thread&id='.$thread['first_post'].'&page='.$page); $main_content .= '<br />Thank you for editing post.<br /><a href="?subtopic=forum&action=show_thread&id='.$thread['first_post'].'">GO BACK TO LAST THREAD</a>'; } } else { $text = $thread['post_text']; $char_id = (int) $thread['author_guid']; $post_topic = $thread['post_topic']; $smile = (int) $thread['post_smile']; } if(!$saved) { if(count($errors) > 0) { $main_content .= '<br /><font color="red" size="2"><b>Errors occured:</b>'; foreach($errors as $error) $main_content .= '<br />* '.$error; $main_content .= '</font>'; } $main_content .= '<br /><form action="?" method="POST"><input type="hidden" name="action" value="edit_post" /><input type="hidden" name="id" value="'.$post_id.'" /><input type="hidden" name="subtopic" value="forum" /><input type="hidden" name="save" value="save" /><table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'"><td colspan="2"><font color="white"><b>Edit Post</b></font></td></tr><tr bgcolor="'.$config['site']['darkborder'].'"><td width="180"><b>Character:</b></td><td><select name="char_id"><option value="0">(Choose character)</option>'; foreach($players_from_account as $player) { $main_content .= '<option value="'.$player['id'].'"'; if($player['id'] == $char_id) $main_content .= ' selected="selected"'; $main_content .= '>'.$player['name'].'</option>'; } $main_content .= '</select></td></tr><tr bgcolor="'.$config['site']['lightborder'].'"><td><b>Topic:</b></td><td><input type="text" value="'.htmlspecialchars($post_topic).'" name="topic" size="40" maxlength="60" /> (Optional)</td></tr> <tr bgcolor="'.$config['site']['darkborder'].'"><td valign="top"><b>Message:</b><font size="1"><br />You can use:<br />[player]Nick[/player]<br />[url=http://address.com/]Address Search - Find Email and Addresses @ Address.com[/url]<br />[img=http://images.com/images3.gif]<br />[code]Code[/code]<br />[b]<b>Text</b>[/b]<br />[i]<i>Text</i>[/i]<br />[u]<u>Text</u>[/u]<br />and smileys:<br />;) , :) , :D , :( , :rolleyes:<br />:cool: , :eek: , :o , :p</font></td><td><textarea rows="10" cols="60" name="text">'.htmlspecialchars($text).'</textarea><br />(Max. 15,000 letters)</td></tr> <tr bgcolor="'.$config['site']['lightborder'].'"><td valign="top">Options:</td><td><label><input type="checkbox" name="smile" value="1"'; if($smile == 1) $main_content .= ' checked="checked"'; $main_content .= '/>Disable Smileys in This Post </label></td></tr></table><center><input type="submit" value="Save Post" /></center></form>'; } } else $main_content .= '<br />You are not an author of this post.'; } else $main_content .= '<br />Post with ID '.$post_id.' doesn\'t exist.'; } else $main_content .= '<br />Your account is banned, deleted or you don\'t have any player with level '.$level_limit.' on your account. You can\'t post.'; } else $main_content .= '<br />Login first.'; } if($action == 'new_topic') { if($logged) { if(canPost($account_logged) || $group_id_of_acc_logged >= $group_not_blocked) { $players_from_account = $SQL->query("SELECT " . $SQL->tableName('players') . "." . $SQL->fieldName('name') . ", " . $SQL->tableName('players') . "." . $SQL->fieldName('id') . " FROM " . $SQL->tableName('players') . " WHERE " . $SQL->tableName('players') . "." . $SQL->fieldName('account_id') . " = ".(int) $account_logged->getId())->fetchAll(); $section_id = (int) $_REQUEST['section_id']; $main_content .= '<a href="?subtopic=forum">Boards</a> >> <a href="?subtopic=forum&action=show_board&id='.$section_id.'">'.$sections[$section_id].'</a> >> <b>Post new thread</b><br />'; if(isset($sections[$section_id])) { if($section_id == 1 && $group_id_of_acc_logged < $group_not_blocked) $errors[] = 'Only moderators and admins can post on news board.'; $quote = (int) $_REQUEST['quote']; $text = trim(codeLower($_REQUEST['text'])); $char_id = (int) $_REQUEST['char_id']; $post_topic = trim($_REQUEST['topic']); $smile = (int) $_REQUEST['smile']; $saved = false; if(isset($_REQUEST['save'])) { $lenght = 0; for($i = 0; $i <= strlen($post_topic); $i++) { if(ord($post_topic[$i]) >= 33 && ord($post_topic[$i]) <= 126) $lenght++; } if($lenght < 1 || strlen($post_topic) > 60) $errors[] = 'Too short or too long topic (short: '.$lenght.' long: '.strlen($post_topic).' letters). Minimum 1 letter, maximum 60 letters.'; $lenght = 0; for($i = 0; $i <= strlen($text); $i++) { if(ord($text[$i]) >= 33 && ord($text[$i]) <= 126) $lenght++; } if($lenght < 1 || strlen($text) > 15000) $errors[] = 'Too short or too long post (short: '.$lenght.' long: '.strlen($text).' letters). Minimum 1 letter, maximum 15000 letters.'; if($char_id == 0) $errors[] = 'Please select a character.'; $player_on_account == false; if(count($errors) == 0) { foreach($players_from_account as $player) if($char_id == $player['id']) $player_on_account = true; if(!$player_on_account) $errors[] = 'Player with selected ID '.$char_id.' doesn\'t exist or isn\'t on your account'; } if(count($errors) == 0) { $last_post = $account_logged->getCustomField('last_post'); if($last_post+$post_interval-time() > 0 && $group_id_of_acc_logged < $group_not_blocked) $errors[] = 'You can post one time per '.$post_interval.' seconds. Next post after '.($last_post+$post_interval-time()).' second(s).'; } if(count($errors) == 0) { $saved = true; $account_logged->set('last_post', time()); $account_logged->save(); $SQL->query("INSERT INTO " . $SQL->tableName('z_forum') . " (" . $SQL->fieldName('first_post') . " ," . $SQL->fieldName('last_post') . " ," . $SQL->fieldName('section') . " ," . $SQL->fieldName('replies') . " ," . $SQL->fieldName('views') . " ," . $SQL->fieldName('author_aid') . " ," . $SQL->fieldName('author_guid') . " ," . $SQL->fieldName('post_text') . " ," . $SQL->fieldName('post_topic') . " ," . $SQL->fieldName('post_smile') . " ," . $SQL->fieldName('post_date') . " ," . $SQL->fieldName('last_edit_aid') . " ," . $SQL->fieldName('edit_date') . ", " . $SQL->fieldName('post_ip') . ") VALUES ('0', '".time()."', '".(int) $section_id."', '0', '0', '".$account_logged->getId()."', '".(int) $char_id."', ".$SQL->quote($text).", ".$SQL->quote($post_topic).", '".(int) $smile."', '".time()."', '0', '0', '".$_SERVER['REMOTE_ADDR']."')"); $thread_id = $SQL->lastInsertId(); $SQL->query("UPDATE " . $SQL->tableName('z_forum') . " SET " . $SQL->fieldName('first_post') . "=".(int) $thread_id." WHERE " . $SQL->fieldName('id') . " = ".(int) $thread_id); header('Location: ?subtopic=forum&action=show_thread&id='.$thread_id); $main_content .= '<br />Thank you for posting.<br /><a href="?subtopic=forum&action=show_thread&id='.$thread_id.'">GO BACK TO LAST THREAD</a>'; } } if(!$saved) { if(count($errors) > 0) { $main_content .= '<font color="red" size="2"><b>Errors occured:</b>'; foreach($errors as $error) $main_content .= '<br />* '.$error; $main_content .= '</font><br />'; } $main_content .= '<form action="?" method="POST"><input type="hidden" name="action" value="new_topic" /><input type="hidden" name="section_id" value="'.$section_id.'" /><input type="hidden" name="subtopic" value="forum" /><input type="hidden" name="save" value="save" /><table width="100%"><tr bgcolor="'.$config['site']['vdarkborder'].'"><td colspan="2"><font color="white"><b>Post New Reply</b></font></td></tr><tr bgcolor="'.$config['site']['darkborder'].'"><td width="180"><b>Character:</b></td><td><select name="char_id"><option value="0">(Choose character)</option>'; foreach($players_from_account as $player) { $main_content .= '<option value="'.$player['id'].'"'; if($player['id'] == $char_id) $main_content .= ' selected="selected"'; $main_content .= '>'.$player['name'].'</option>'; } $main_content .= '</select></td></tr><tr bgcolor="'.$config['site']['lightborder'].'"><td><b>Topic:</b></td><td><input type="text" name="topic" value="'.htmlspecialchars($post_topic).'" size="40" maxlength="60" /> (Optional)</td></tr> <tr bgcolor="'.$config['site']['darkborder'].'"><td valign="top"><b>Message:</b><font size="1"><br />You can use:<br />[player]Nick[/player]<br />[url=http://address.com/]Address Search - Find Email and Addresses @ Address.com[/url]<br />[img=http://images.com/images3.gif]<br />[code]Code[/code]<br />[b]<b>Text</b>[/b]<br />[i]<i>Text</i>[/i]<br />[u]<u>Text</u>[/u]<br />and smileys:<br />;) , :) , :D , :( , :rolleyes:<br />:cool: , :eek: , :o , :p</font></td><td><textarea rows="10" cols="60" name="text">'.htmlspecialchars($text).'</textarea><br />(Max. 15,000 letters)</td></tr> <tr bgcolor="'.$config['site']['lightborder'].'"><td valign="top">Options:</td><td><label><input type="checkbox" name="smile" value="1"'; if($smile == 1) $main_content .= ' checked="checked"'; $main_content .= '/>Disable Smileys in This Post </label></td></tr></table><center><input type="submit" value="Post Thread" /></center></form>'; } } else $main_content .= 'Board with ID '.$board_id.' doesn\'t exist.'; } else $main_content .= 'Your account is banned, deleted or you don\'t have any player with level '.$level_limit.' on your account. You can\'t post.'; } else $main_content .= 'Login first.'; }
  5. BrendonPawn

    Banco de dados com relação 1:N

    Olá usuários do fórum imasters! Estou atualmente estudando a manipulação de dados em um banco de dados, em específico o MySQL. Estou usando recursos nativos, ou como se diz, fazendo na mão. Isso quer dizer que não estou usando ferramentas, frameworks, etc... para trabalhar com os bancos, tabelas e dados. Quero entender de perto como funciona na raiz, para depois fazer uso de ferramentas que aceleram a produção. No momento estou com bastante dúvidas sobre a relação de 1:N (um para muitos) já estudei vários artigos na internet mas me parecem muito confusos... Sei que é meio estúpido pedir código pronto aqui, más será que alguém poderia criar um exemplo para mim bem claro? A situação é a seguinte: CREATE TABLE usuarios ( id INT AUTO_INCREMENT PRIMARY KEY, nome VARCHAR(32) NOT NULL ); CREATE TABLE veiculos ( id INT AUTO_INCREMENT PRIMARY KEY, marca VARCHAR(32) NOT NULL, kmrodados DECIMAL(13, 1) NOT NULL DEFAULT 0, dono INT NULL ); INSERT INTO usuarios (id, nome) VALUES (1, 'Brendon'), (2, 'João'), (3, 'Maria'); INSERT INTO veiculos (id, marca, kmrodados, dono) VALUES (1, 'FIAT', 35000.4, 1), (2, 'FORD', 25432.6, 1), (3, 'CHEVROLET', 2500.1, 2); Nesse cenário, como ficaria uma query SELECT para conseguir um resultado semelhante a esse? { id: 1, nome: 'Brendon', veiculos: [ { id: 1, marca: 'FIAT', kmrodados: 35000.4 }, { id: 2, marca: 'FORD', kmrodados: 25432.6 } ] }, { id: 2, nome: 'João', veiculos: [ { id: 3, marca: 'CHEVROLET', kmrodados: 2500.1 } ] }, { id: 3, nome: 'Maria', veiculos: [] } Desde já agradeço a todos interessados em ajudar!
  6. gersonab

    Consulta aparece em um servidor, no outro não.

    Boa tarde, tenho uma consulta onde retorno dados de várias tabelas, em um servidor ela funciona perfeitamente, no outro não retorna os campos longtext, fica vazio. <?php $id=(int)$_GET['idc']; $consulta3 = $pdo->query("SELECT * FROM proc INNER JOIN cli ON idc=part LEFT JOIN posicao ON idpos=posic WHERE idc=$id"); while($user3 = $consulta3->fetch(PDO::FETCH_ASSOC)){ $idpr = $user3['idpr']; $reup = $user3['reup']; //// vários campos, todos retornando normal $leb = str_replace('"','-',$user3['leb']); $obsp = str_replace('"','-',$user3['obsp']); ?> <p>Andamento : <?php echo nl2br($obsp);?> </p> /// não retorna, ou <p>Andamento : <?php echo $obsp;?> </p> /// também não retorna porém no servidor que eu trabalho funciona normalmente já no servidor do cliente que é na kinghost o mesmo não retorna estes dados, o que pode ser ?
  7. Hugo Lima

    Ajuda, Update de Legenda em upload de multiplas fotos?

    Eu tenho um sistema que, depois de carregar várias fotos, gera um campo de legendas para cada foto, desejo atualizar o banco de dados dessas legendas. Como fazer isso. Minha tabela no banco de dados - tabela tb_fotos_portfolio (id, id_portfolio, legenda, arquivo). Obs.: Seria apenas a parte de UPDATE das legendas no banco de dados. ... <?php $sql = "SELECT * FROM tb_fotos_portfolio WHERE id_portfolio = $id"; $query = $DB->Select($sql); if (count($query) == 0) { ?> <div class="box-body"> <h3 class="text-center text-danger" style="margin: 140px 0;">Imagem não enviada!</h3> </div> <?php } else { ?> <div class="box-body no-padding"> <ul class="users-list clearfix"> <?php foreach($query as $item) { ?> <li> <a class="popup-link" href="../../../upload/portfolio/imagem/<?php echo $item['arquivo']; ?>"> <img src="../../../upload/portfolio/miniatura/<?php echo $item['arquivo']; ?>" alt="<?php echo $item['arquivo']; ?>"/> <span class="users-list-name"><?php echo $item['arquivo']; ?></span> </a> <a class="btn btn-label btn-danger btn-xs" href="acoes.php?acao=deleteFotos&id=<?php echo $_GET['id'];?>&arquivo=<?php echo $item['arquivo'];?>"><i class="fal fa-trash-alt"></i>Excluir</a> <span class="users-list-name"><?php echo $item['legenda']; ?></span> <form id="" action="acoes.php?acao=legendas_fotos" method="post" enctype="multipart/form-data"> <input type="text" name="legenda[]" id="legenda" class="form-control" placeholder="Legenda" value="<?php echo $item['legenda']; ?>"/> </li> <?php } ?> </ul><!-- /.users-list --> </div> <button type="submit" class="btn btn-success btn-label btn-sm"><i class="fa fa-check"></i> Atualizar Legendas</button> </form> .... acao.php case 'legendas_fotos': $legenda = $_POST['legenda']; $sql = "UPDATE tb_fotos_portfolio SET legenda= $legenda WHERE id=:id"; $vCampos = array('id'=>$id); $DB->Execute($sql, $vCampos); // Volta para o form header("location:form.php?id=" . $id); exit; break
  8. Moacir Guilherme Filho

    Numeração de protocolo sequencial

    Olá, possuo um formulário PHP para inserir em uma tabela no banco MySQL. Preciso criar uma função (PHP ou JAVA) semelhante ao "auto increment" para preencher um campo na minha tabela no banco que seja semelhante a isso, quando for inserindo: 0001/2020, 0002/2020, 0003/2020, porém ao virar o ano a numeração tem que zerar, ficando assim: 0001/2021, 0002/2021, 0003/2021. Formulário tem o nome "cad_ocorrencia.php", o banco "sisgcm", a tabela "atendimento" e o campo da tabela "numero_ocorrencia". No MySQL a tabela está assim: atendimento (id_atentidmento, numero_ocorrencia, datainicio e hora inicio). Obs: A função tem que funcionar como o auto increment porque o sistema será usado por mais de uma pessoa e se a função fizer a consulta no banco na hora que o formulário for aberto, poderá causar duplicidade de numero de ocorrência, então deve ser executada igualmente ao auto incremento.Desde já agradeço meus Mestres deste site.
  9. ddsb

    Problema Mysql não recebe os dados no BD

    Tenho um formulário no meu site e o BD estava recebendo as informações normalmente durante alguns dias. Depois de alguns cadastros ele parou de receber. Não alterei nada nos códigos, mas apareceu uma pasta .wellknown/ACMEchallenge no public_html, não sei se isso tem alguma relação com o fato de ter parado de receber os cadastros. Como posso resolver?
  10. Rafael Ferreira_163968

    variavel php curl

    Boa noite, nunca mechi com curl e estou tomando uma surra bunita, se puderem me ajudar, estou consumindo uma api e preciso enviar dados do mysql para esta api, mas antes estou tentando testar com variaveis feitas a mao sem conectar no BD, funcionando com as variaveis eu desenrolo a consulta depois. segue codigo e duvida: <?php $curl = curl_init(); $numero = '000000000'; $msg = 'teste de mensagem BD'; curl_setopt_array($curl, array( CURLOPT_URL => "http://urldaapi", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "{\r\n \"menssage\": '.$msg.',\r\n \"number\": '.$numero.'\r\n}", CURLOPT_HTTPHEADER => array( "Authorization: 0000000000000000000", "cache-control: no-cache" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } nessa linha CURLOPT_POSTFIELDS => "{\r\n \"menssage\": '.$msg.',\r\n \"number\": '.$numero.'\r\n}", a original é a seguinte CURLOPT_POSTFIELDS => "{\r\n \"menssage\": \"Teste pela API\",\r\n \"number\": \"6200000000\"\r\n}", gostaria da ajuda dos colegas de como pegar essas variaveis $numero = '000000000'; e $msg = 'teste de mensagem BD'; e repassar elas para o CURLOPT_POSTFILDES, tentei como a primeira linha mas nao da, preciso modificar a linha original para consumir esses valores. podem me ajudar?
  11. Olá senhoras e senhores, venho aqui tirar uma dúvida ! Eu desenvolvi um projeto em php para um cliente e hospedei na Hostgator, como já trabalho com a hospedagem Hostgator há alguns anos, nunca tive problema até quando comecei a trabalhar com PREPARE STATEMENT , e aí me gerou uma grande dor de cabeça, e como não tinha muita experiência usando instrução preparada, comecei a desenvolver meus projetos através desta instrução e rodando de boa localmente, e foi só hospedar remotamente e já deu alguns erros, e o principal de foi * Call to undefined method mysqli_stmt::get_result() in * e consultando o site stackoverflow li um seguinte trecho de um desenvolvedor experiente que: O mysqli foi introduzido no php 5, já a função get_result pertence ao pacote mysqlnd que é o driver nativo. E como não tinha ciência desta função MYSQLND e pelo que eu li, ELA É NATIVA DO MYSQL, e para não perder o plano já contratado, tive que usar em vez de get_result() usar o bind_result (), só que tive dificuldades de alguns dias para resolver, mas consegui fazer com que na classe A, onde esta minhas instruções e conexões com o banco e o loop do while estão , fazer que ao instanciar um objeto e chamar cada variável usando [ ] como array conseguisse pegar todos os dados dentro do loop do while e irei mostrar logo abaixo: E a minha dúvida é saber se estaria fazendo de forma correta ou existiria outra forma de usar o foreach para percorrer um array. Segue abaixo o código de exemplo: CLASSE A: <?php class DadosAmortecedoresEletricos { private $conecta_banco; public function __construct(){ $this->conecta_banco=new Conexao(); $this->conecta_banco->Conectar(); } public $ativo; public $com_foto; public $sem_foto; public $linha; public $id; public $produto_id; public $negocio; public $negocio_tipo; public $tipos; public $tipo; public $imgP; public $valor; public $negocio_d; public $sqlL_2; public $sqlL_1; // ESSA CLASSE SERVE PARA PAGINAÇÃO public function BuscarDadosAmortecedoresEletricos(){ $conexao=$this->conecta_banco->banco; $Dados=new DadosEmpresa(); $Dados->BuscarDadosEmpresa(); $limit=$Dados->qtd_secao_eletrico; $ativo=$this->ativo=1; $sql_1=$conexao->prepare("SELECT i.id,i.id_produto_tipo,i.id_produto_subtipo,t.tipo,n.tipo_nome FROM dados_anuncio i LEFT JOIN tipo_produto t ON (t.id = i.id_produto_tipo)LEFT JOIN subtipo_produto n ON (n.id = i.id_produto_subtipo) WHERE i.ativo=? AND n.tipo_nome LIKE '%el%' ORDER BY i.id DESC LIMIT ".$limit.""); $sql_1->bind_param('s',$ativo); $sql_1->execute(); $sqlL_1=$sql_1->bind_result($id,$id_produto_tipo,$id_produto_subtipo,$tipo, $tipo_nome); while ($sql_1->fetch()) { $this->produto_id=$id_produto_tipo; $this->subproduto_id=$id_produto_subtipo; } $dados=""; $ativo=$this->ativo=1; // ESSA CLASSE SERVE PARA RESGATAR OS DADOS $sql_1 = $conexao->prepare("SELECT i.id AS idi,i.id_produto_tipo,i.foto_exibicao,i.foto_grande,foto_titulo,i.valor, t.tipo_nome, n.tipo AS tipo FROM dados_anuncio i LEFT JOIN subtipo_produto t ON (t.id = i.id_produto_subtipo) LEFT JOIN tipo_produto n ON (n.id =".$this->produto_id.") WHERE i.ativo=? AND t.tipo_nome LIKE '%el%' AND i.id_produto_subtipo LIKE '%".$this->subproduto_id."%' ORDER BY RAND () LIMIT ".$limit."") ; if($sql_1){ $sql_1->bind_param('s',$ativo); $sql_1->execute(); $sql_1->store_result(); $this->sqlT_3=$sql_1->bind_result($id,$id_produto_tipo,$foto_exibicao,$foto_grande,$foto_titulo,$valor, $tipo_nome, $tipo); while ($sql_1->fetch()) { $this->id[]=$id; $this->tipo[]=$tipo; $this->tipo_nome[]=$tipo_nome; $this->foto_exibicao[]=$foto_exibicao; $this->foto_grande[]=$foto_grande; $this->foto_titulo[]=$foto_titulo; $this->valor[]=$valor; } }} } ?> Minha página onde instancio o objeto abaixo: <?php // Aqui é onde uso os foreach para percorrer cada variável $n=0; $tipos=array(); $n=0; foreach ($dados_elet->id as $key=> $thing) { $tipos[$n][1] = $thing; $n++; } if(is_array($dados_elet->tipo)){ $n=0; foreach ($dados_elet->tipo as $thing) { $tipos[$n][2] = $thing; $n++; }} if(is_array($dados_elet->tipo_nome)){ $n=0; foreach ($dados_elet->tipo_nome as $thing) { $tipos[$n][3] = $thing; $n++; }} if(is_array($dados_elet->foto_exibicao)){ $n=0; foreach ($dados_elet->foto_exibicao as $thing) { $tipos[$n][4] = $thing; $n++; }} if(is_array($dados_elet->foto_grande)){ $n=0; foreach ($dados_elet->foto_grande as $thing) { $tipos[$n][5] = $thing; $n++; }} if(is_array($dados_elet->foto_titulo)){ $n=0; foreach ($dados_elet->foto_titulo as $thing) { $tipos[$n][6] = $thing; $n++; }} if(is_array($dados_elet->valor)){ $n=0; foreach ($dados_elet->valor as $thing) { $tipos[$n][7] = $thing; $n++; }} foreach($tipos as $dados_inf){ $imgP= $dados_inf[4]; $descricao= $dados_inf[6]; $id= $dados_inf[1]; $negocio= $dados_inf[2]; $negocio_id= $dados_inf[2]; $subtipo= $dados_inf[3]; $negocio_tipo= $dados_inf[2]; $tipos= $dados_inf[2]; $valor= $dados_inf[7]; if($valor=='0.00' || $valor==''){$valor='Consulte-nos';}else{ $valor ="R$ ".$valor;} $tipo= $tipos;$tipo= strtolower(str_replace(" ","-",strtr(utf8_decode(trim($tipo)),utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-"))); $imgP2='img_produtos/thumbs/'.$imgP.''; if(file_exists($imgP2)){$foto='<img class="lozad" data-src="'.$Dados->site.'img_produtos/thumbs/'.$imgP.'" alt="'.$tipo.'" />';}else{$foto='<img src="'.$Dados->site.'images/sem_foto.jpg" alt="'.$tipo.'" />';} echo $com_foto='<ul class="menu"><div class="favoritos_add"> <a data-id="'.$id.'" data-toggle="modal" title="'.$id.'" data-target="#myModalfavoritos'.$id.'" id="'.$id.'" class="hvr-pulse"><img src="images/coracao_fav_ext.png" alt="Favoritos" /></a></div> <li><a title="'.$tipo.' | valor: '.$valor.'" href="'.$Dados->site.'contato">'.$foto.'</a> <div class="fundo_dados"> <div class="dados_tipo">'.$tipos.' </div> <div class="dados_subtipo">'.$subtipo.'</div> <div class="dados_titulo">'.$descricao.'</div> <div class="dados_valor">'.$valor.'</div> <div class="informacoes"><a title="'.$negocio.' | '.$tipo.'| valor: '.$valor.'" href="'.$Dados->site.'contato">MAIS INFORMAÇÕES</a></div> <div class="comparar"> <label><input name="comparar[]" type="checkbox" id="comparar" value="'.$id.'" /> Comparar</label><div class="dados_codigo">código: '.$id.'</div></div> </div></li></ul>'; ?> Notem que para cada variável eu uso um foreach para varrer as informações do while da outra página e por último eu uso um foreach que pega cada variável do foreach e distribuo as informações de cada variável na sua matriz na ordenação de [1] , [2], [3] e assim por diante. Resumindo , funciona mas queria saber se existe outra maneira com menos linha de código e que fique mais rápido na hora do php compilar .. Lembrando que não posso usar GET_RESULLT(). E acredito que muitos terão este problema quando começarem a atualizar seus códigos.. Obrigado :)
  12. Pessoal achei muitos exemplos na internet do que eu quero porém somente com type date ou timestamp. Tenho uma tabela onde tenho uma coluna 'altera' (type datetime), ou seja, ' 2020-05-06 11:00:00' Preciso que minha consulta retorne todos os itens que estiverem entre a data de hoje (type datetime) e até 30 dias anteriores a data atual. Tentei varias formas, imagino que seja algo assim: SELECT * FROM `tabela` WHERE `altera` <= (NOW() - 30 days) ORDER BY `altera` DESC
  13. gersonab

    Criar um evento na linha do checkbox

    Bom dia meus amigos, estou precisando criar um evento numa linha de dados de uma consulta, sendo que esta linha deveria estar selecionada através do checkbox, tipo : Tenho uma listagem de informações de clientes, nesta lista tenho um checkbox para selecionar uma única linha, nesta podendo fazer alterações conforme um select option, sendo que este não esta na linha, esta fora dela, pois se eu tiver 3000 linhas, terei 3000 select option, logo o que eu preciso é pegar o id da linha e enviar para o select , onde ali escolherei a ação a tomar. não estou sabendo pesquisar ou dar uma partida para este, desde já agradeço a ajuda. <div class="action-btns d-none"> <div class="btn-dropdown mr-1 mb-1"> <div class="btn-group dropdown actions-dropodown"> <button type="button" class="btn btn-white px-1 py-1 dropdown-toggle waves-effect waves-light" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Ação </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#"><i class="feather icon-trash"></i>Editar</a> <a class="dropdown-item" href="#"><i class="feather icon-archive"></i>Inserir imagem</a> <a class="dropdown-item" href="#"><i class="feather icon-file"></i>Email</a> <a class="dropdown-item" href="#"><i class="feather icon-save"></i>Deletar</a> </div> </div> </div> </div> <div class="table-responsive"> <table class="table"> <thead> <tr> <th></th> <th>IMAGEM</th> <th>NOME</th> <th>CATEGORIA</th> <th>EMAIL</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" id="id" name="id" /></td> <td><img src="../cli/imagem.png" alt="img"></td> <td>Nome do cliente</td> <td>Categoria</td> <td>Email</td> </tr> <!-- aqui continua a lista, resumida para facilitar -->
  14. gustavoolrosa2019

    BOT PRIDE - Open Source , deixe sua opiniao

    Atualmente trabalho como desenvolvedor full-stack e finalizei um projeto pessoal e iniciei este ao qual o titulo se refere. O projeto pride consiste no desenvolvimento de um bot com diversas opções de ferramentas e interações com o usuário. É um projeto com um escopo firme e bem organizado, nada amador eu busco a excelência em tudo que faço. Gostaria que dessem uma olhada no escopo e dessem a opinião de voces, ideias para ferramentas e funcionalidades e coisas do tipo. E se quiserem participar é um projeto open-source, fiquem a vontade! Link: https://gitlab.com/gustavoolrosa2019/bot-pride
  15. djwagnersp

    Item select no loop While

    Boa noite galera, tudo bem? Estou com uma duvida, poderiam me ajudar. Acredito que seja simples resolver, no entanto ainda sou novato não tenho certeza como fazer.. tenho o seguinte código: <div class="row"> <div class="col s12"> <ul class="collapsible"> <?php $sql_lotes = "SELECT * FROM tbl_lotes WHERE `eve_cod` = $eveId AND lot_ativo = 'S'"; $conn = $mysqli->query($sql_lotes) or die($mysqli->error); while($dados = $conn->fetch_array()){ $lot_cod = $dados['lot_cod']; $lot_nome = $dados['lot_nome']; ?> <li> <div class="collapsible-header"> <!-- Nome do Lote se pista/camarote/areavip --> <h5 class="pink-text text-darken-4"><?php echo $dados['lot_nome']; ?></h5> </div> <div class="collapsible-body"> <?php $sql_item_lotes = "SELECT * FROM tbl_item_lotes WHERE `lot_cod` = $lot_code AND item_lot_ativo = 'S'"; $conn = $mysqli->query($sql_item_lotes) or die($mysqli->error); $dados = $conn->fetch_array()){ $item_lot_cod = $dados['ite_lot_cod']; $item_lot_nome = $dados['ite_lot_nome']; ?> <!-- fazer um loop e trazer todos os itens lote meia/inteira --> <span>ITEM DO LOTE</span> </div> </li> <?php } ?> </ul> </div> </div> Preciso de mais um loop nos item lote como fazer esse novo laço?
  16. Edilson Chaves

    Criar um novo registro com CURSOR no MySql

    Ola amigos, uso curso a algum tempo, só que desta vez estou apanhando de algo que aparentemente e bem simples. Tenho certeza que estou esquecendo algum detalhe. To a 2 dias me debatendo com isto. Por isto estou pedindo ajuda. O que pretendo fazer e criar um novo registro que mostre a evoluçao do crecimento mensal projetando o ponto de equilibrio. Para isto eu preciso pegar a soma do mês anterior e acrescentar a soma do atual. Esta é a Procedure. Abaixo explico o quer nao esta funcionado. DROP PROCEDURE IF EXISTS sp_Monitorado; DELIMITER $$ CREATE PROCEDURE sp_Monitorado() BEGIN DECLARE done INT DEFAULT FALSE; DECLARE vVlrMesAtuPrv, vVlrMesAntPrv, vVlrMesAtuRea, vVlrMesAntRea, vPrevisto, vRealizado numeric(10,2); DECLARE vAnoAtu, vMesAtu, vOrdem, vAno, vMes INT; DECLARE vGrupo, vSubGrupo, vPessoa, vPessoaAtu VARCHAR(100); DECLARE cDados CURSOR FOR SELECT Ordem, Grupo, SubGrupo, Pessoa, Ano, Mes, Previsto, Realizado FROM vwresultadomonitoramento; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cDados; read_loop: LOOP FETCH cDados INTO vOrdem, vGrupo, vSubGrupo, vPessoa, vAno, vMes, vPrevisto, vRealizado; IF done THEN LEAVE read_loop; END IF; IF vOrdem <= 4 THEN SET vVlrMesAtuPrv = vVlrMesAtuPrv + vPrevisto; SET vVlrMesAtuRea = vVlrMesAtuRea + vRealizado; INSERT INTO zzResultado VALUES (vOrdem, vGrupo, vSubGrupo, vPessoa, vAno, vMes, vPrevisto, vVlrMesAtuPrv); END IF; IF vOrdem = 4 THEN SET vVlrMesAntPrv = vVlrMesAntPrv + vVlrMesAtuPrv; SET vVlrMesAntRea = vVlrMesAntRea + vVlrMesAtuRea; INSERT INTO zzResultado VALUES (99, vGrupo, 'PONTO DE EQUILIBRIO', vPessoa, vAno, vMes, vVlrMesAntPrv, vVlrMesAntRea); SET vVlrMesAtuPrv = 0; SET vVlrMesAtuPrv = 0; END IF; END LOOP read_loop; CLOSE cDados; END; $$ DELIMITER; Quando co cursor entra nesta condiçao abaixo ele deveria pegar o valor acumulado anterior e acrescentar as variaveis (vVlrMesAntPrv, vVlrMesAntRea). So que o valor se perde e fica tudo zerado. Alguém pode me dizer onde estou errando. Anexo tem um print do resultado que pretendo ter IF vOrdem = 4 THEN SET vVlrMesAntPrv = vVlrMesAntPrv + vVlrMesAtuPrv; SET vVlrMesAntRea = vVlrMesAntRea + vVlrMesAtuRea; INSERT INTO zzResultado VALUES (99, vGrupo, 'PONTO DE EQUILIBRIO', vPessoa, vAno, vMes, vVlrMesAntPrv, vVlrMesAntRea); SET vVlrMesAtuPrv = 0; SET vVlrMesAtuPrv = 0; END IF;
  17. Alberto Nascimento

    Contar registros com critérios mysql PHP

    Tenho o seguinte código que faz a consulta e contagem de todos os campos de uma tabela e retorna a quantidade através de ECHO. Porém preciso que tenha dois critérios a seguir para então contar: <?php $servidor = ""; $usuario = ""; $senha = ""; $dbname = ""; $conn = mysqli_connect($servidor, $usuario, $senha, $dbname); if(!conn) { echo "Error"; } $sql="SELECT count(id) AS total FROM tbl_test"; $result=mysqli_query($conn,$sql); $values=mysqli_fetch_assoc($result); $num_rows=$values['total']; echo $num_rows; ?> Só que preciso que primeiro encontre todos os registros que tiverem o nome "ALBERTO" no campo NOME e logo em seguida faça a contagem dos registros de acordo com o campo SITUACAO . Ficaria desta forma a ser exibido: Obrigado !!
  18. Matheus B. Siqueira

    [ Resolvido ] Falha ao retornar dados com PDO

    Meu PDO, não está retornando nenhum valor, e está dando erro ao tentar baixar o arquivo: <?php //se não tiver o parametro, mata a aplicação. if (isset($_POST['codigo_video'])) { $codigo_video = $_POST['codigo_video']; } //Aqui está um exemplo simples de como fazer uma conexão PDO $host = 'localhost'; $db = 'onteach'; $user = 'root'; $pass = 'root'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; try { $pdo = new PDO($dsn, $user, $pass); } catch (PDOException $e) { throw new PDOException($e->getMessage(), (int)$e->getCode()); } //$pdoQuery = $pdo->query("SELECT conteudo.arquivo FROM conteudo WHERE conteudo.conteudo_video = '{$codigo_video}'"); try{ $ready = $pdo->prepare("SELECT conteudo.arquivo FROM conteudo WHERE conteudo.conteudo_video = :codigo_video"); $ready->bindParam(':codigo_video', $codigo_video); // $ready = $pdo->prepare($pdoQuery); // $ready->execute(); }catch(PDOException $e){ echo $e->getMessage(); } while($rs = $ready->fetch(PDO::FETCH_ASSOC));{ $local = 'upload/'; $local_arquivo = $local.$rs; header('Content-type: octet/stream'); // Indica o nome do arquivo como será "baixado". Você pode modificar e colocar qualquer nome de arquivo header('Content-disposition: attachment; filename="'.$rs.'";'); // Indica ao navegador qual é o tamanho do arquivo header('Content-Length: '.filesize($local_arquivo)); // Busca todo o arquivo e joga o seu conteúdo para que possa ser baixado readfile($local_arquivo); } print_r($rs); ?> Alguém sabe resolver? Visto que o $rs não retorna o dado arquivo da tabela
  19. helkton

    passar varios valores foreach

    oi galera, seguinte preciso salvar os dados de um carrinho no banco de dados olha só como fiz a gambiarra, me ajudem a consertar rsss array_map ( function ($id,$qdade,$valor) { echo 'idProd '.$id; echo ' qdadeProd '.$qdade; echo ' valorProd '.$valor; echo '<br>'; },$idProduto, $qdadeProduto, $valorProduto); já tenho os dados gravados no banco em um carrinho temporario agora depois que o cliente finalizar o pagamento eu quero jogar esses dados na tabela pedidos a saida esta pegando esses devidos valores $id - $qdade e $valor certinho mais não consigo jogar no banco de dados
  20. viniciuslemmos

    Ultimo registro de cada categoria

    SELECT MAX(`noticias`.`noticia_id`) AS `Nnoticia_id`, MAX(`categoria`.`imagem`) AS `Cimagem`, MAX(`categoria`.`nome`) AS `Cnome`, MAX(`noticias`.`titulo`) AS `Ntitulo`, MAX(`noticias`.`data_criacao`) AS `Ndata_criacao`, MAX(`categoria`.`url`) AS `Curl`, MAX(`noticias`.`url`) AS `Nurl` FROM `noticias` INNER JOIN `categoria` WHERE `noticias`.`categoria_id` = `blog`.`categoria_id` GROUP BY `noticias`.`categoria_id` ORDER BY `noticia_id` DESC Como consigo a ultima noticia de cada categoria? Nessa acima o titulo que imprime não é o ultimo
  21. Marcones Borges

    [Resolvido] Consulta com parametro

    Boa noite, estou quebrando cabeça com uma consulta e não consigo passar ela... vou postar meu código. $conexao = conexao::getInstance(); $sql = 'SELECT * FROM novo_exercicio WHERE id = :id'; $stm = $conexao->prepare($sql); $stm->bindValue(':id', $id); $stm->execute(); $cliente = $stm->fetch(PDO::FETCH_OBJ); if(!empty($cliente)): // Formata a data no formato nacional //$array_data = explode('-', $cliente->data_nascimento); //$data_formatada = $array_data[2] . '/' . $array_data[1] . '/' . $array_data[0]; endif; endif; $area_nova = $cliente->area; function montaSelect(){ $sql1 = "SELECT * FROM campos WHERE area=$area_nova"; $query = mysql_query( $sql1 ); if( mysql_num_rows( $query ) > 0 ){ while( $dados = mysql_fetch_assoc( $query ) ){ $opt .= '<option value="'.$dados['campo'].'">'.$dados['campo'].'</option>'; } } else $opt = '<option value="0">Nenhum cliente cadastrado</option>'; return $opt; } ?> Quando eu removo o parametro WHERE area=$area_nova, ele exibe tudo, quando eu ensiro este parametro ele não exibe nada. quando dou um echo =$area_nova, ele exibe o nome que é o filtro certinho... o que estou fazendo errado?
  22. Good

    Estrutura para Comissionamento

    Boa noite, tenho uma dúvida e gostaria da opinião pensando sempre em grande fluxo. Ex.: tenho um banco de dados, com tabela chamada pagamentos. Dentro dela tem as informações como usuário, valor, status, etc. Eu preciso colocar comissão para alguns usuários. Vocês acham melhor eu criar uma nova tabela chamada pagamentos_comissao? Ou criar uma coluna dentro da tabela pagamentos e armazenar para puxar como array depois? obs.: vou ter alguns pagamentos que a comissão vai ser para 2 ou mais usuários. Qual dos 2 modos é o mais viável?
  23. Josueweb

    Onde estou errando? colocar variavel no php/mysql

    $result = mysqli_query($connect, "INSERT INTO '$login' SET '$msg'='$message'");
  24. gersonab

    Autocomplete só mostra após segundo nome

    Bom dia, utilizo um sistema de auto complete que funciona quase que perfeitamente, porque quase, se eu tenho 10 Marias cadastradas o autocomplete só inicia após eu colocar uma letra do segundo nome e ou sobrenome, tipo : se eu escrever Maria somente, não aparece opções na lista; agora se eu escrever Maria A - ja começa a aparecer opções na lista; tem como iniciar as opções após uma terceira letra digitada ? segue o código que utilixo. form <label class="field"> <input type="text" name="nomec" id="nomec" class="gui-input"> <input type="hidden" name="idc" id="idc"> </label> ajax $( "#nomec" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "../lista/autocli.php", type: 'post', dataType: "json", data: { search: request.term }, success: function( data ) { response( data ); } }); }, select: function (event, ui) { $('#nomec').val(ui.item.label); $('#idc').val(ui.item.value); return false; } }); autocli.php require_once('config.php'); if(isset($_POST['search'])){ $search = $_POST['search']; $query = "SELECT DISTINCT nomec AS nomec, idc FROM cli WHERE nomec like'%".$search."%'"; $result = mysqli_query($con,$query); $response = array(); while($row = mysqli_fetch_array($result) ){ $response[] = array("value"=>$row['idc'],"label"=>$row['nomec']); } echo json_encode($response); } exit; desde já agradeço.
  25. ma_gr

    PHP MySQL update se arquivos forem enviados

    Boa tarde, tudo certo?! Estou querendo montar uma query de update de uma forma mais otimizada, sem precisar usar tantos if's. No meu formulário o usuário irá, da primeira vez, obrigatoriamente ter que enviar a imagem do perfil, documento com foto e comprovante de residência (arquivos de imagens). Já nas próximas vezes em que o usuário puder alterar suas informações, os arquivos poderão ser substituídos ou não, ficando a cargo do usuário. Da primeira vez eu atualizo o status quando as imagens são enviadas. Pensei em fazer uma concatenação caso !empty() mas penso que deva ter uma forma melhor de se fazer, além do que eu teria que fazer outros if's para o bind_param(). Espero ter sido claro. Minha consulta seria basicamente: $updateData = "UPDATE members SET username=?, lastname=?, nickname=?, emailOpt=?, address=?, number=?, neighborhood=?, city=?, state=?, country=?, cep=?, phone=?, cellphone=?, cpf=?, rg=?, born=?, facebook=?, instagram=?, profile_img=?, profileImgStatus=?, doc_img=?, docStatus=?, address_img=?, addressImgStatus=? WHERE userId = ? "; $stmt = $mysqli->prepare($updateData); $stmt->bind_param( 'sssssssssssssssssssis', $username, $lastname, $nickname, $emailOpt, $address, $number, $neighborhood, $city, $state, $country, $cep, $phone, $cellphone, $cpf, $rg, $born, $facebook, $instagram, $profile_img, $profileImgStatus, $doc_img, $docStatus, $address_img, $addressImgStatus, $userId );
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.