segunda-feira, 19 de junho de 2017

MySQL check valid e-mail - checagem de email validos na base

Segue REGEX bem simples:

SELECT `email` 
 FROM  `clients`  
WHERE `email` NOT REGEXP '^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';
 
 

quarta-feira, 10 de maio de 2017

Form checkbox array PHP and MySQL - Multiple Values - Passa multiplos valores em um form

<?php
// SIMPLES
$go='';
if (isset($_POST['go'])   $go=$_POST['go'];
if (!$go)
{
?>
<form method='post' action='".$_SERVER['PHP_SELF']."'>
<table>
<tr>
                <td><input type='checkbox' name='apagar[]' value='1' /></td>
                <td><input type='checkbox' name='apagar[]' value='2' /></td>
                <td><input type='checkbox' name='apagar[]' value='3' /></td>
                <td><input type='checkbox' name='apagar[]' value='4' /></td>
</tr>
<tr>
                <td colspan=4 align='center'>
                <input type='hidden' name='go' value='S' />
                <input type='submit' name='apagando' value='Apagar Selecionados' />
                </td>
</table>
</form>
<?php
exit;
}
else
{
 $i=0;
    if (isset($_POST['apagando']))
    {
       $apagar = $_POST['apagar'];
       foreach ($apagar as $del=>$value)
       {
            $sql=mysql_query("delete from SUA_TABELA_SQL where id='$value'");
            if ($sql) $i++;
       }
       if ($i>0)
       {
           echo "sucesso";
       }
      else
       {
           echo "nada foi feito";
       }
    }
exit;
}
// PASSAR MULTIPLOS VALORES

echo "
<form data-form-output='orm-output-global' data-form-type='forms' method='post' action='".$_SERVER['PHP_SELF']."'>
    <div>
        <div>
            <label for='forms-mensagem'>Réponse</label><textarea  id='forms-mensagem' name='resposta[][346][]'></textarea>
        </div>
        <div>
            <label for='forms-mensagem'>Réponse</label><textarea  id='forms-mensagem' name='resposta[][374][]'></textarea>
        </div>
        <div>
            <input type='submit' name='Enviar' value='Enviar' />
        </div>
    </div>
</form>";
echo '</div></form>';

if (!empty($_POST['Enviar']))
{
   
    if (!empty($_POST['resposta'])) $resposta = $_POST['resposta'];
    foreach ($resposta as $resp=>$value)
    {
        $resposta2 = $_POST['resposta'][$resp];
        foreach ($resposta2 as $resp2=>$value2)
        {
            //echo "$resp2<br/>";
        }
        $resposta3 = $_POST['resposta'][$resp][$resp2];
        foreach ($resposta3 as $resp3=>$value3)
        {
            //echo "$value3<br/>";
        }
      
        echo "$resp2-->$value3<br/>";
    }
   
   
}



?>

JavaScript Onchange return old value - onchange retornar valor antigo

Meu problema é:

Tenho x numero de Containers e y numero de Pedidos.

Pedidos não pode ser maior que Containers então tenho:

OBS: IE não suporta Number.parseInt() por isso usei apenas parseInt().

<script language="Javascript" type="text/javascript">
function validar_totais(pedido, container)
{
    if (parseInt(pedido)<=parseInt(container))
    {
    //faça algo legal aqui
    var my_condition = true;
    }
    else
    {
        alert ("Quantidade de Pedidos não pode ser maior que a Quantidade de Contêineres.");
        var my_condition = false;
    }
       
        var lastSel = $("#qtd_geral_pedido option:selected");
        $("#qtd_geral_pedido").change(function(){
          if(my_condition)
          {
            lastSel.prop("selected", true);
          }
        });

        $("#qtd_geral_pedido").click(function(){
            lastSel = $("#qtd_geral_pedido option:selected");
        });
}
</script>
<?php
echo "
Containers:
           <select name='quantidade' id='quantidade'>
               <option value='0'>---</option> ";
            for ($i=1;$i<=200;$i++)
               {
                      echo "<option value='$i'>$i</option>\n";
                }
echo "
            </select>
Pedidos:
            <select name='qtd_geral_pedido' id='qtd_geral_pedido'  onchange='validar_totais(document.procurado.qtd_geral_pedido.value, document.procurado.quantidade.value);'>
                   <option value='0'>--</option>";
            for ($i=1;$i<=200;$i++)
               {
                      echo "<option value='$i'>$i</option>\n";
                }
                        echo "
             </select>
        ";
?>


terça-feira, 21 de março de 2017

PHP trocar ENTER - ch(10) ou ch(13) por <br> | change enter tab to <br>


O problema aqui era o envio da nota por e-mail, com str_replace dava alguns paus e como eu uso um disparo de notas vindas de um banco de dados passei a usar a linha abaixo e funcionou perfeitamente.

The problem here was sent an e-mail, I tried str_replace but sometimes it just crash the configuration.

$nota="Especializados em fornecer end-to-end soluções complexas e softwares, a nossa empresa é considerada um parceiro fundamental para todas as empresas e organizações que trabalharam conosco.

Com profissionais qualificados e com vasto conhecimento em desenvolvimento e consultoria. Nossa equipe é composta de Arquitetos de Software, Desenvolvedores de Software, Administradores de Dados, Administradores de Sistema, Web Designers e Gerentes de Projeto. ";

$output = nl2br($nota);


quarta-feira, 14 de dezembro de 2016

Regex against Google Analytics Spam Bots - Regex para tentar frear Spam no Google Analytics


Lembrar de Clicar no ADMINISTRADOR -> Vista de Propriedade -> Visualizar Configurações ->

Filtragem de bots
Excluir todos os hits de bots e indexadores conhecidos

Depois entre em Relatórios -> E crie um Novo Segmento ->

clique em + Adicionar Segmento
clique em + Novo Segmento
Escolha Avançado -> Condições -> Em "Ações do Evento" escolha Titulo da Página e em "Contém" escolha "corresponde à Regex" no meu caso todos os abaixo estavam entrando no seu vc precisa verificar e colar apenas uma parte do nome deles no regex abaixo.

Cada | (pipe) é um Spammer.

\W*((?i)sharebutton|xyz|reddit|lifehacĸer|Secret|motherboard|ilovevitaly|thenextweb(?-i))\W*

Lembrando que não é uma solução definitiva, o correto seria o Google apagá-los automaticamente...

Então de tempos em tempos seu regex vai aumentar, pois vc terá que ficar inserindo os nomes dos novos spammers.

Remember to click the ADMINISTRATOR -> View Property -> View Settings ->

Bottling bots
Delete all hits from known bots and crawlers

Then go to Reports -> And create a new Segment ->

Click + Add Segment
Click + New Segment
Choose Advanced -> Conditions -> In "Event Actions" choose Page Title and in "Contains" choose "corresponds to Regex" in my case all below were entering your you need to check and paste only a part of their name in the Regex below.

Each | (Pipe) is a Spammer.

\W*((?i)sharebutton|xyz|reddit|lifehacĸer|Secret|motherboard|ilovevitaly|thenextweb(?-i))\W*

Remembering that it is not a definitive solution, the correct one would be Google to automatically delete them ...

Then from time to time your regex will increase, because you will have to be entering the names of the new spammers.


quinta-feira, 2 de junho de 2016

HTML 5 - POP UP



<!DOCTYPE html>
<head>
    <title>Creating a modal window with HTML5 &amp; CSS3</title>
   
    <style>
     #openModal {
    position:relative;
    z-index:1;
   
    }
    #popup
{
    position:absolute;
    z-index:2;
    left:300px;
    top:35px;
    display:none;
    width:500px;
   
        padding: 5px 20px 13px 20px;
        border-radius: 10px;
        background: -moz-linear-gradient(#fff, #999);
        background: -webkit-linear-gradient(#fff, #999);
        background: -o-linear-gradient(#fff, #999);
}


    .close {
        background: #606061;
        color: #FFFFFF;
        line-height: 25px;
        position: absolute;
        right: -12px;
        text-align: center;
        top: -10px;
        width: 24px;
        text-decoration: none;
        font-weight: bold;
        -webkit-border-radius: 12px;
        -moz-border-radius: 12px;
        border-radius: 12px;
        -moz-box-shadow: 1px 1px 3px #000;
        -webkit-box-shadow: 1px 1px 3px #000;
        box-shadow: 1px 1px 3px #000;
    }

    .close:hover { background: #00d9ff; }
  
    </style>
   
</head>

<body>

<div id="popup">
        <div>
        <a href="#close" onclick="hide('closer'); hide('popup')" id="closer" title="Close" class="close">X</a>
        <h2>Modal Box</h2>
        <p>This is a sample modal box that can be created using the powers of CSS3.</p>
        <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
    </div>
</div>   

<div id="openModal" class="modalDialog">
   
        <h2>TESTE</h2>
        <p>POP UP CSS3.</p>
        <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>

</div>


<script>
    document.getElementById('popup').style.display = 'block';
   
    function hide(id)
    {
    document.getElementById(id).style.display = "none";
    }
   
    </script>
</body>
</html>

MySQL How to fill a Google Drive Spread Sheet - Como preencher o Planilhas do Google Drive



 // This app is made in JDBC

// Replace the variables in this block with real values.
var address = 'localhost:3306';
var user = 'USER';
var userPwd = 'PWD';
var db = 'DATABASE';

var dbUrl = 'jdbc:mysql://' + address + '/' + db;

//Gets and Sets the Current Spreadsheet as Active
var doc = SpreadsheetApp.getActiveSpreadsheet();
doc.setActiveSheet(doc.getSheetByName('Sheet1')); // nome da sheet
//No meu caso tenho a nome da coluna na linha 1: [E-mail] na coluna A1 e [Contato] na coluna B1
var lastRow = doc.getLastRow();
var lastRow_plus = lastRow + 1; // pula uma linha
var cell = doc.getRange('A'+lastRow_plus); // acha a ultima linha preenchida da coluna A

// Read up to 1000 rows of data from the table and log them.
function readFromTable() {
  var conn = Jdbc.getConnection(dbUrl, user, userPwd);

  var start = new Date();
 
  var stmt = conn.createStatement();
  stmt.setMaxRows(1000);
  var results = stmt.executeQuery('SELECT DISTINCT email, contato FROM `SUA-TABELA` WHERE status_envio=0 order by email');
  var numCols = results.getMetaData().getColumnCount();
  var row = 0;
  while (results.next()) {
    var rowString = '';
    for (var col = 0; col < numCols; col++) {
      cell.offset(row, col).setValue(results.getString(col+1));
    }
    row++;
    Logger.log(rowString);
  }
  var stmt1 = conn.prepareStatement('update SUA-TABELA set status_envio=1');
  stmt1.addBatch();
  var batch = stmt1.executeBatch();
 
  results.close();
  stmt.close();

  var end = new Date();
  Logger.log('Time elapsed: %sms', end - start);
}


quinta-feira, 11 de fevereiro de 2016

quinta-feira, 29 de outubro de 2015

Find part of a string in text - Achar parte do texto numa string


A coluna estado na tabela serviços estava vazia e precisava ser preenchida, eu tinha os estados na tabela ddds.

Coluna "fone" na tabela "serviços":
+55 11 4553-0400
+55 31 4553-0400

Coluna "estado" e "ddd" na tabela "ddds":
SP, 11
MG, 31
...

update servicos, ddds set servicos.estado=ddds.estado where MID(fone,4,3)= ddds.ddd


quinta-feira, 20 de agosto de 2015

Array em ordem alfabética Brasil - Array Usort (character accentuation)


Primeiro coloque no topo do pagina
First on the top of the page

setlocale(LC_ALL, "pt_BR", "ptb"); // works for Linux and Windows

Depois monte sua página

function cmp($a, $b) {
    return strcmp($a["first_name"], $b["first_name"]);
}

$docs = array(
    1 => array(
        'first_name' => 'Márcia Amanda',
        'crm' => 4321,
        'job' => 'Médica',
        'sex' => 'f'
    ),
    2 => array(
        'first_name' => 'Pedro Alexandre',
        'crm' => 6789,
        'job' => 'Veterinário',
        'sex' => 'm'
    ),
    3 => array(
        'first_name' => 'Lívia Pereira',
        'crm' => 8765,
        'job' => 'Obstetra',
        'sex' => 'f'
    )
);

usort($docs, "cmp", SORT_LOCALE_STRING);

                                $qtas_pessoas = count($docs);
                              
                                $j=1;
                               
                                while (list($key, $value) = each($docs)) {
                               
                                if ($j==1) echo "<div class='wrapper indent-bottom7-1'>";
                               
                                $dr='';
                                if ($value["sex"]=='m') $dr='Dr.';
                                else $dr='Dra.';
                               
                                echo "
                                <div class='grid_4 alpha'>
                                    <h6 class='p2'>$dr ".$value["first_name"]."<br/>CRM ".$value["crm"]."</h6>
                                    ".$value["job"]."
                                </div>\n
                                ";
                               $j++;
                               if ($j>$qtas_pessoas) {
                                   echo "</div>";
                                   break; // TEMOS APENAS X PESSOAS...
                               }
                               // quebrar sempre de 3 em 3
                               if ($j % 3 == 1) echo "</div><div class='wrapper indent-bottom7-1'>";
                                }

quinta-feira, 18 de setembro de 2014

PHP Caminhos do Dominio

// Retorna o domínio do servidor
echo $_SERVER['SERVER_NAME'] . "<br />";
// Retorna o path do arquivo onde está sendo executado
echo $_SERVER['PHP_SELF'] . "<br />";
// Retorna o path do pasta onde está sendo executado
echo $_SERVER['DOCUMENT_ROOT'] . "<br />";
// Retorna o path do arquivo onde está sendo executado o script
echo $_SERVER['SCRIPT_FILENAME'] . "<br />";
// Retorna o path e nome do arquivo que está executando
echo $_SERVER['SCRIPT_NAME'] . "<br />";
 
echo "<hr >";
$path = $_SERVER['SCRIPT_FILENAME'];
$path_parts = pathinfo($path);
// retorna o path absoluto do diretório no servidor
echo $path_parts['dirname'] . "<br />";
// retorna o nome do arquivo com extensão
echo $path_parts['basename'] . "<br />";
// retorna a extensão do arquivo
echo $path_parts['extension'] . "<br />";
// retorna o nome do arquivo sem extensão
echo $path_parts['filename'] . "<br />";

Linux bash file returns unexpected token `$'do\r''

open file in vi edit with   vi filename.sh   command; type in vi  :set ff=unix  command; save file with  :wq It will save the file with unix...