Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

capango

alguem pode me ensinar como criar codigo de post, partilha e like

Recommended Posts

este é o add.php

<?php
session_start();
include_once("functions.php");
include_once('conecta.php');
 
$userid = $_SESSION['userid'];
$body = substr($_POST['body'],0,140);
 
add_post($userid,$body);
$_SESSION['message'] = "o teu post foi adicionado!";
 
header("Location:index.php");
?>

 

 

este é cadastro.php

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cadastro de usuário</title>
</head>
 
<body>
<h1>Cadastro de Usuário</h1>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" name="cadastro" >
Nome:<br />
<input type="text" name="nome" /><br /><br />
Email:<br />
<input type="text" name="email" /><br /><br />
Foto de exibição:<br />
<input type="file" name="foto" /><br /><br />
<input type="submit" name="cadastrar" value="Cadastrar" />
</form>
</body>
</html>

 

 

este é conecta.php

 

<?php 
$conexao = mysqli_connect('localhost', 'root', '', 'loja');
?>

 

este é a função.php

<?php
function add_post($userid,$body){
    $sql = "insert into posts (user_id, body, stamp)
            values ($userid, '". mysql_real_escape_string($body). "',now())";
 
    $result = mysql_query($sql);
}

function show_posts($userid,$limit=0){
    $posts = array();
    $user_string = implode(',', $userid);
    $extra =  " and id in ($user_string)";
 
    if ($limit > 0){
        $extra = "limit $limit";
    }else{
        $extra = '';    
    }
 
    $sql = "select user_id, body, stamp from posts
        where user_id in ($user_string)
        order by stamp desc $extra";
    echo $sql;
    $result = mysql_query($sql);

    while($data = mysql_fetch_object($result)){
        $posts[] = array(   'stamp' => $data->stamp,
                            'userid' => $data->user_id,
                            'body' => $data->body
                    );
    }
    return $posts;
 
}

// esta funçaõ mostra todos os usuarios do sistema 


// esta funçaõ fara o usuario deixar de seguir 
function following($userid){
    $users = array();
 
    $sql = "select distinct user_id from following
            where follower_id = '$userid'";
    $result = mysql_query($sql);
 
    while($data = mysql_fetch_object($result)){
        array_push($users, $data->user_id);
 
    }
 
    return $users;
 
}
// esta funçaõ fara a verificaçaõ se ha relacionamento nesta tabela seguir ou deixar de segui 
 
function check_count($first, $second){
    $sql = "select count(*) from following
            where user_id='$second' and follower_id='$first'";
    $result = mysql_query($sql);
 
    $row = mysql_fetch_row($result);
    return $row[0];
 
}
 
function follow_user($me,$them){
    $count = check_count($me,$them);
 
    if ($count == 0){
        $sql = "insert into following (user_id, follower_id)
                values ($them,$me)";
 
        $result = mysql_query($sql);
    }
}
 
 
function unfollow_user($me,$them){
    $count = check_count($me,$them);
 
    if ($count != 0){
        $sql = "delete from following
                where user_id='$them' and follower_id='$me'
                limit 1";
 
        $result = mysql_query($sql);
    }
}

// esta funçaõ exibir uma lista de outros usuários que o usuário está 
//seguindo na página inicial. Já existe uma função show_users() , mas isso mostra todos os usuários.

function show_users($user_id=0){
 
    if ($user_id > 0){
        $follow = array();
        $fsql = "select user_id from following
                where follower_id='$user_id'";
        $fresult = mysql_query($fsql);
 
        while($f = mysql_fetch_object($fresult)){
            array_push($follow, $f->user_id);
        }
 
        if (count($follow)){
            $id_string = implode(',', $follow);
            $extra =  " and id in ($id_string)";
 
        }else{
            return array();
        }
 
    }
 
    $users = array();
    $sql = "select id, username from users
        where status='active'
        $extra order by username";
 
 
    $result = mysql_query($sql);
 
    while ($data = mysql_fetch_object($result)){
        $users[$data->id] = $data->username;
    }
    return $users;
    
}


?>

 

 

funçao.php

<?php
$SERVER = 'localhost';
$USER = 'root';
$PASS = '';
$DATABASE = 'loja';
 
 
if (!($mylink = mysql_connect( $SERVER, $USER, $PASS))){
    echo  "<h3>Sorry, could not connect to database.</h3><br/>
    Please contact your system's admin for more help\n";
    exit;
}

 

 

 

index.php

<?php
session_start();

include_once('functions.php');
include_once('conecta.php');
 
$_SESSION['userid'] = 1;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Postes Listit</title>
</head>
<body>
<p><a href='users.php'>Veja a lista de usuarios</a></p>
 
<?php
if (isset($_SESSION['message'])){
    echo "<b>". $_SESSION['message']."</b>";
    unset($_SESSION['message']);
}
?>
<form method='post' action='add.php'>
<p>Your status:</p>
<textarea name='body' rows='5' cols='40' wrap=VIRTUAL></textarea>
<p><input type='submit' value='submit'/></p>
</form>

<?php
$posts = show_posts($_SESSION['userid']);
 
if (count($posts)){
?>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($posts as $key => $list){
    echo "<tr valign='top'>\n";
    echo "<td>".$list['userid'] ."</td>\n";
    echo "<td>".$list['body'] ."<br/>\n";
    echo "<small>".$list['stamp'] ."</small></td>\n";
    echo "</tr>\n";
}
?>
</table>
<?php
}else{
?>
<p><b>Ainda não postaste nada!</b></p>
<?php
}
?>

<h2>Users you're following</h2>
 
<?php
$users = show_users($_SESSION['userid']);
 
if (count($users)){
?>
<ul>
<?php
foreach ($users as $key => $value){
    echo "<li>".$value."</li>\n";
}
?>
</ul>
<?php
}else{
?>
<p><b>nao esta seguindo ninguem!</b></p>
<?php
}
?>

 
</body>
</html>

 

 

 

user.php

<?php
session_start();
include_once("header.php");
include_once("functions.php");
 
?>

<body>
 
<h1>List of Users</h1>
<?php
$users = show_users();
$following = following($_SESSION['userid']);
 
if (count($users)){
?>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($users as $key => $value){
    echo "<tr valign='top'>\n";
    echo "<td>".$key ."</td>\n";
    echo "<td>".$value;
    if (in_array($key,$following)){
        echo " <small>
        <a href='action.php?id=$key&do=unfollow'>unfollow</a>
        </small>";
    }else{
        echo " <small>
        <a href='action.php?id=$key&do=follow'>follow</a>
        </small>";
    }
    echo "</td>\n";
    echo "</tr>\n";
}
?>
<p><b>There are no users in the system!</b></p>
<?php
}
?>
</body>
</html>

 

action.php

<?php
session_start();
include_once("conecta.php");
include_once("functions.php");
 
$id = $_GET['id'];
$do = $_GET['do'];
 
switch ($do){
    case "follow":
        follow_user($_SESSION['userid'],$id);
        $msg = "You have followed a user!";
    break;
 
    case "unfollow":
        unfollow_user($_SESSION['userid'],$id);
        $msg = "You have unfollowed a user!";
    break;
 
}
$_SESSION['message'] = $msg;
 
header("Location:index.php");
?>

 

produtos_view.php

 <body> 
        <!-- Fixed navbar -->
        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Celke</a>
                </div>
                <div id="navbar" class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a href="#">Home</a></li>
                        <li><a href="#about">About</a></li>
                        <li><a href="#contact">Contact</a></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                            <ul class="dropdown-menu">
                                <li><a href="#">Action</a></li>
                                <li><a href="#">Another action</a></li>
                                <li><a href="#">Something else here</a></li>
                                <li role="separator" class="divider"></li>
                                <li class="dropdown-header">Nav header</li>
                                <li><a href="#">Separated link</a></li>
                                <li><a href="#">One more separated link</a></li>
                            </ul>
                        </li>
                    </ul>
                </div><!--/.nav-collapse -->
            </div>
        </nav>
        <div class="container theme-showcase" role="main">
            <div class="page-header">
                <h1>Vitrine de produtos</h1>
            </div>

            <?php
            require('./conf/Config.inc');
            $read = new Read;
            $read->ExeRead('produtos', 'LIMIT :limit', 'limit=12');

            View::Load('conf/view/produtos');
            ?>
            <div class="row"> <?php
                foreach ($read->getResult() as $produto):
                    extract($produto);
                    View::Show($produto);
                endforeach;
                ?>
            </div>

        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
    </body>
</html>

 

 

 

 

produto.add.php

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Celke - Upload</title>
        <!--<link href="css/bootstrap.css" rel="stylesheet">-->
    </head>
    <body> 
        <?php
        require('./conf/Config.inc');
        $addinfo = filter_input_array(INPUT_POST, FILTER_DEFAULT);
        if ($addinfo && $addinfo['addArquivo']):
            unset($addinfo['addArquivo']);
            $addinfo['imagem'] = ($_FILES['imagem']['tmp_name'] ? $_FILES['imagem'] : null);
            $file = $_FILES['imagem'];

            $artigo = new Produto();
            $artigo->CreateProdutos($addinfo);
            if (!$artigo->getResult()):                
                echo $artigo->getMsg();
            else:
                $upload = new Upload();
                $upload->Imagem($file, 'produtos/'.$artigo->getResult().'/');
                 echo $artigo->getMsg();
            endif;
        endif;
        ?>

        <form name="addArquivoForm" action="" method="post" enctype="multipart/form-data">
            <label><span>Titulo</span>
                <input type="text" name="titulo"/><br><br>
            </label>
            <label><span>Conteúdo</span>
                <input type="text" name="conteudo"/><br><br>
            </label>
            <label><span>Imagem</span>
                <input type="file" name="imagem"/><br><br>
            </label>
            <input type="submit" name="addArquivo" value="Cadastrar Arquivo"/>
        </form>
    </body>
</html>

 
mysql_select_db( $DATABASE );
?>

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

este é o DB

-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 03-Fev-2018 às 23:06
-- Versão do servidor: 10.1.28-MariaDB
-- PHP Version: 7.1.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `loja`
--

-- --------------------------------------------------------

--
-- Estrutura da tabela `following`
--

CREATE TABLE `following` (
  `user_id` int(11) NOT NULL,
  `follower_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Estrutura da tabela `posts`
--

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `body` varchar(140) NOT NULL,
  `stamp` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Estrutura da tabela `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(8) NOT NULL,
  `status` enum('active','inactive') NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Estrutura da tabela `usuarios`
--

CREATE TABLE `usuarios` (
  `id` int(11) NOT NULL,
  `nome` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `foto` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Extraindo dados da tabela `usuarios`
--

INSERT INTO `usuarios` (`id`, `nome`, `email`, `foto`) VALUES
(8, 'faael', 'faelcalves@hotmail.com', '2dd945d3c0471656ce5f0a4bb587bcbf.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `following`
--
ALTER TABLE `following`
  ADD PRIMARY KEY (`user_id`,`follower_id`);

--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `usuarios`
--
ALTER TABLE `usuarios`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `usuarios`
--
ALTER TABLE `usuarios`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Tudo bem pessoal?
       
      No código abaixo, estou fazendo uma consulta nas tabelas, banners e banners_referencia
      Meu objetivo é trazer resultados com valores iguais ao nome da cidade declarada na $cidade ou resultados com a referencia Total.
      O problema é que está trazendo todos os resultados. Tenho 10 linhas, 1 com o nome da cidade e duas com o valor Total, então o resultado teria que ser de apenas 3 linhas, mas mostra tudo.
       
      $banner = "SELECT A.*, B.* FROM banners A, banners_referencia B WHERE B.cod_referencia = A.cod_referencia AND A.cidade = '$cidade' OR B.referencia = 'Total' ORDER BY RAND()";
      $banner = mysqli_query($conexao, $banner) or die ("Banner não encontrado");
      while($busca= mysqli_fetch_array($banner)){
          print $busca['cidade'].'<br>';
      };
       
      Alguém consegue me ajudar?
    • Por Rafael_Ferreira
      Não consigo carregar a imagem do captcha do meu formulário. Foi testado com o xampp e easyphp. Também não carregou a imagem de outros captcha. 
       
       
    • Por luiz monteiro
      Olá.
      Estou atualizando meu conhecimento com Front-End e me deparei com o seguinte problema.
      Criei um sistema para fazer o upload de imagens e alguns campos text.
      Algo bem simples para depois começar a estudar javascript para mostrar a miniatura....
      Mas quando saio do navegador Chrome ou da aba por mais de 3 minutos, ao retornar o navegador as vezes atualiza ou nem chega atualizar mas limpa os campos.
      Estou usando um Smart Motorola com Android, mas um amigo testou no iPhone e acontece a mesma coisa.
      Gostaria de saber se há como usar javascript para evitar isso?
      Agradeço desde já.

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Uploader</title>
      </head>
      <body>
          <form action="?" method="post" enctype="multipart/form-data">
              <br><br>
              <div>selecione a imagem 1</div>
              <input type="file" name="foto1" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem1">
              
              <br><br>
              <input type="file" name="foto2" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem2">
              
              <br><br>

              <input type="file" name="foto3" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem3">
              
              <br><br>
              <input type="submit" value="Enviar">
              <br><br>
          </form>
      <?php
      if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
          vardump ($_FILES);
      }
      ?>
      </body>
      </html>
       
       
       
    • Por luiz monteiro
      Olá, tudo bem?
       
      Estou melhorando meu conhecimento em php e mysql e, me deparei com o seguinte. A tabela da base de dados tem um campo do tipo varchar(8) o qual armazena números. Eu não posso alterar o tipo desse campo. O que preciso é fazer um select para retornar o números que contenham zeros a direita ou a esquerda.
      O que tentei até agora
       
      Ex1
      $busca = $conexao->prepare("select campo form tabela where (campo = :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form']);
       
      Se a direita da string $_REQUEST['campo_form'] termina ou inicia com zero ou zeros, a busca retorna vazio.
      Inseri dados numéricos, da seguinte maneira para testar: 01234567;  12345670: 12345678: 12340000... entre outros nessa coluna. Todos os valores que não terminam ou não iniciam com zero ou zeros, o select funciona.
       
       
      Ex2
      $busca = $conexao->prepare("select campo form tabela where (campo = 0340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex3
      $busca = $conexao->prepare("select campo form tabela where (campo = '02340001' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex4
      $busca = $conexao->prepare("select campo form tabela where (campo like 2340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex5
      $busca = $conexao->prepare("select campo form tabela where (campo like '12340000') ");
      Esse número está cadastrado, mas não retorna.
       
      Ex6
      $busca = $conexao->prepare("select campo form tabela where (campo like '"12340000"' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex7
      $busca = $conexao->prepare("select campo form tabela where (campo like :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form'])
      Não retorna dados.
       
      O  $_REQUEST['campo_form'] é envio via AJAX de um formulário. 
      Usei o gettype para verificar o post, e ele retorna string.
      Fiz uma busca com número 12345678 para verificar o que o select retorna, e também retrona como string.
       
      Esse tipo de varchar foi usado porque os números que serão gravados nesse campo,  terão zeros a direita ou na esquerda. Os tipos number do mysql não gravam zeros, então estou usando esse. O problema é a busca.
      Agradeço desde já.
       
       
×

Informação importante

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