0

I insert a row with following commands :

create.php

<?php 
require_once 'db_connect.php';
if($_POST) {       
    $validator = array('success' => false, 'messages' => array());

    $a = $_POST['id'];
    $b = $_POST['number'];

    $sql = "INSERT INTO class (id, number) 
    SELECT '$a', '$b'
    WHERE EXISTS (SELECT * FROM members WHERE idmember = $a AND active = 1)";
    $query = $connect->query($sql);

    if($query === TRUE) {           
        $validator['success'] = true;
        $validator['messages'] = "Message : OK!";       
    } else {        
        $validator['success'] = false;
        $validator['messages'] = "Message : ERROR!";
    }

    $connect->close();
    echo json_encode($validator);
}

When I add a field to this table, that active is = 1, i do not have a problem and the row is added. When I add a field to this table, that active is = 0, The row will not be added to the database mysql, But "Message : OK!" is shown. why?

solmaz ahamdi
  • 150
  • 1
  • 11
  • Under what circumstances does `$connect->query($sql);` return true or false? If it only returns false on errors (rather than on queries that didn't insert a row), then you'll always hit the "OK" message. – iainn Jul 04 '17 at 14:09
  • $query is correcly executed in both the case .. .. in both the case you have a proper sql statements so the result is true .. evtually change the number of selected row .. – ScaisEdge Jul 04 '17 at 14:14
  • 2
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Jul 04 '17 at 14:14
  • 1
    mysql never lies. If `OK` is shown, all went well. If no row is added, maybe is it because there was nothing found with `idmember = $a AND active = 1` – Kaddath Jul 04 '17 at 14:14
  • main thing your select query no data but main query run so this is problem – Shafiqul Islam Jul 04 '17 at 14:19
  • Your code is correct. Check table corresponding columns. Whether you added correct column name or not? For me, Your code is working. Just checked. – Nana Partykar Jul 04 '17 at 14:48
  • I checked. The data was found,I'm really confused. On the table class , there is a trigger (AFTER INSERT). Is it relevant? – solmaz ahamdi Jul 04 '17 at 15:54
  • @scaisEdge how? Could you explain a little bit more about that? – solmaz ahamdi Jul 04 '17 at 16:00
  • @Quentin Thanks for your reminder – solmaz ahamdi Jul 04 '17 at 16:01
  • The query() return false on failure alias worng sql command (with sintax or other error) ... your command are in both the case valid sql command . the commands don'r return any errors – ScaisEdge Jul 04 '17 at 16:17
  • that's exactly right, How when not added, Show Error? is there a solution? – solmaz ahamdi Jul 04 '17 at 16:25

0 Answers0