-2

I have this code:

$pegaDados = mysql_query("SELECT * FROM curso WHERE cpf='$cpf'");

        if(mysql_num_rows($pegaDados) > 0){
          echo '<script type="text/javascript">alert("CPF já cadastrado em nosso Banco de Dados!");</script>';
        }
        else{

I want to transform it on PDO, but I'm facing problems. Can anyone help me?

I'm looking a solution on the web, I didn't find the "best" solution for it. Look my conection file below:

    <?php

define( 'MYSQL_HOST', '???' );
define( 'MYSQL_USER', '???' );
define( 'MYSQL_PASSWORD', '???' );
define( 'MYSQL_DB_NAME', '???' );

try
{
 $PDO = new PDO( 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}

catch ( PDOException $e )
{
 echo 'Erro ao conectar com o MySQL: ' . $e->getMessage();
}

?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Might [rowCount](http://php.net/manual/en/pdostatement.rowcount.php) help? – aynber Jun 21 '17 at 13:32
  • I think yes... I just need to alert the user, if the data was in database. – Hebert Richard Masseno Dias Jun 21 '17 at 13:34
  • @aynber `rowCount()` will not work for SELECT queries in PDO – Jay Blanchard Jun 21 '17 at 13:41
  • 1
    @JayBlanchard Thanks, I'd forgotten. It's been so long since I worked with straight PDO. – aynber Jun 21 '17 at 13:41
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php). – Jay Blanchard Jun 21 '17 at 13:46

3 Answers3

0

Some database drivers with PDO have no natural row count function (rowCount() is only for INSERT, UPDATE or DELETE queries) , so you have to use another method. Here is what I use (EDIT :updated connection based on OP's information)

$sql = 'select * from table';
$data = $PDO->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);

Then you can test:

if($num_rows > 0){
    // your code here
}

EDIT Updated code based on new information from OP:

$sql = "SELECT * FROM curso WHERE cpf = :cpf"; 
$stmt = $PDO->prepare( $sql ); 
$stmt->bindParam( ':cpf', $cpf ); 
$result = $stmt->execute(); 
$rows = $result->fetchAll(); 
$num_rows = count($rows);
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 1
    Please share it then @sidyll `rowCount()` is only valid for INSERT, UPDATE and DELETE queries, not SELECT. *[PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.](http://php.net/manual/en/pdostatement.rowcount.php)* – Jay Blanchard Jun 21 '17 at 13:36
  • Fatal error: Call to a member function query() on a non-object in – Hebert Richard Masseno Dias Jun 21 '17 at 13:52
  • `rowCount()` does work for `SELECT` if the database supports it. Your answer should mention that, and these days it has a high chance of working anyway if you're using recent software. In MySQL for example which is highly popular, it works. And in case it does not, then using a `SELECT COUNT(*)` and then `fetchColumn()` is more efficient than `SELECT *`, even though the `fetchAll()` might be optimised by the driver. – sidyll Jun 21 '17 at 13:52
  • 2
    Since you didn't post your PDO code I have no idea what your connection is called @CyberPlague – Jay Blanchard Jun 21 '17 at 13:53
  • You're right to a degree @sidyll, but there are no guarantees and PHP records that in their docs. If the OP needs to use the data then doing one query and fetching is more efficient than 2 queries. – Jay Blanchard Jun 21 '17 at 13:54
  • Sure, and you know...to many assumptions here since the OP is not clear at all. Anyway, my initial _"yes it has"_ is in reply to _"PDO has no natural row count function"_. It does have, it's just that some drivers/databases might not support the implementation but then it's not PDO's fault by itself, if you understand what I mean. And judging by OP's Portuguese this seems to be a form processing and data won't be used, just checked for existence (hence my comment about `COUNT()`) but again...too many things we don't know here :) – sidyll Jun 21 '17 at 14:01
  • Agreed @sidyll ¯\\_(ツ)_/¯ – Jay Blanchard Jun 21 '17 at 14:02
  • @CyberPlague I updated my answer based on your connection information. Remember to replace my query with your query. – Jay Blanchard Jun 21 '17 at 14:05
  • `$sql = 'SELECT * FROM curso WHERE cpf = :cpf'; $data = $PDO->query($sql); $rows = $data->fetchAll(); $num_rows = count($rows); if($num_rows > 0){ echo ''; }` – Hebert Richard Masseno Dias Jun 21 '17 at 14:11
  • Fatal error: Call to a member function fetchAll() on a non-object in – Hebert Richard Masseno Dias Jun 21 '17 at 14:12
  • Because you have not accounted for `:cpf` which you would need to do with `bindParam()` – Jay Blanchard Jun 21 '17 at 14:13
  • You have to bind a parameter and prepare for the first query too @CyberPlague – Jay Blanchard Jun 21 '17 at 14:25
  • `$sql = "SELECT * FROM curso WHERE cpf = :cpf"; $stmt = $PDO->prepare( $sql ); $stmt->bindParam( ':cpf', $cpf ); $result = $stmt->execute(); $data = $PDO->query($sql); $rows = $data->fetchAll(); $num_rows = count($rows); if($num_rows > 0){ echo ''; } else{` The same problem... =( – Hebert Richard Masseno Dias Jun 21 '17 at 14:34
  • I'm terrible on PDO... sorry! – Hebert Richard Masseno Dias Jun 21 '17 at 14:35
  • Quit dumping code in comment, it is nearly unreadable. `$sql = "SELECT * FROM curso WHERE cpf = :cpf"; $stmt = $PDO->prepare( $sql ); $stmt->bindParam( ':cpf', $cpf ); $result = $stmt->execute(); $rows = $result->fetchAll(); $num_rows = count($rows);` – Jay Blanchard Jun 21 '17 at 14:40
-1

I just changed the :cpf variable to $cpf, and it works!

<?php

require '../conexao.php';

$nome               =           addslashes ($_POST['nome']);
$foto               =           addslashes ($_POST['foto']);
$cpf                =           addslashes ($_POST['cpf']);
$rg                 =           addslashes ($_POST['rg']);
$email              =           addslashes ($_POST['email']);
$telefone           =           addslashes ($_POST['telefone']);
$endereco           =           addslashes ($_POST['endereco']);
$bairro             =           addslashes ($_POST['bairro']);
$cidade             =           addslashes ($_POST['cidade']);
$estado             =           addslashes ($_POST['estado']);
$observacoes        =           addslashes ($_POST['observacoes']);
$curso              =           addslashes ($_POST['curso']);

$newquery = "SELECT * FROM curso WHERE cpf = $cpf";

$data = $PDO->query($newquery);
$rows = $data->fetchAll();
$num_rows = count($rows);

if($num_rows > 0){
    echo '<script type="text/javascript">alert("CPF já cadastrado em nossa base de dados!");</script>';
}

else{

$sql = "INSERT INTO curso SET foto = :foto, nome = :nome, email = :email, cpf = :cpf, rg = :rg, telefone = :telefone, endereco = :endereco, bairro = :bairro, cidade = :cidade, estado = :estado, observacoes = :observacoes, curso = :curso";

$stmt = $PDO->prepare( $sql );
$stmt->bindParam( ':foto', $foto );
$stmt->bindParam( ':nome', $nome );
$stmt->bindParam( ':email', $email );
$stmt->bindParam( ':cpf', $cpf );
$stmt->bindParam( ':rg', $rg );    
$stmt->bindParam( ':telefone', $telefone );
$stmt->bindParam( ':endereco', $endereco );
$stmt->bindParam( ':bairro', $bairro );
$stmt->bindParam( ':cidade', $cidade );
$stmt->bindParam( ':estado', $estado );
$stmt->bindParam( ':observacoes', $observacoes );
$stmt->bindParam( ':curso', $curso );
$result = $stmt->execute();

echo '<script type="text/javascript">alert("Matrícula realizada com sucesso!");</script>';
echo "<script>window.location = 'https://pag.ae/bck57zw';</script>";

}

?>

-2

You should try this one

$sql = "SELECT * FROM curso WHERE cpf='$cpf'";
$pegaDados = $con->prepare($sql);
$pegaDados->execute();
if($pegaDados->rowCount() > 0){
    echo '<script type="text/javascript">alert("CPF já cadastrado em nosso Banco de Dados!");</script>';
}

$con is your database connection.

  • Turn the tide against teaching/propagating sloppy and dangerous coding practices. If you post an answer without prepared statements [you may want to consider this before posting](http://meta.stackoverflow.com/q/344703/). Additionally [a more valuable answer comes from showing the OP the right method](https://meta.stackoverflow.com/a/290789/1011527). You copied a bad query from another answer. And, if you're going to prepare a query you should use placeholders to actually prep the variable. – Jay Blanchard Jun 21 '17 at 13:48
  • My connection is in an external file. – Hebert Richard Masseno Dias Jun 21 '17 at 13:56
  • Ok then you can pass your connection variable in constructor and store in a private variable. – Hemant Anjana Jun 21 '17 at 13:58