-2

I have a problem with the php file below.When I click Send button, it shows a new window that says that the connection is ok and informations added to the database, but when I check the database, neither name nor email have been added. Will you please help me out to understand what's the problem?

<html>

<body>
<?php


$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');

    $servername = "127.0.0.1";
    $username = "username";
    $password = "password";
    $dbname = "Subscription";
    $con = mysql_connect($servername,$username,$password,$dbname);
    if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }


    echo "Connected successfully";
    mysql_select_db("Subscription", $con);
    $name = false;
    if (isset($_POST['name'])) { $name = $_POST['name'];

    $email = false;
    if (isset($_POST['email'])) { $name = $_POST['email'];
 }
}

    echo "'You have been successfully added.' . '<br>'; ";

mysql_close($con)

?>
</body>

</html>

this is the code I used after the suggested corrections:

$con = mysql_connect($servername,$username,$password,$dbname);
    if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }


    echo "Connected successfully";
      mysql_select_db("Subscription", $con);

    $sql =  
$sql = "INSERT INTO newsletter (name, email) VALUES ('".mysql_real_escape_string($_POST['name'])."','".mysql_real_escape_string($_POST['email'])."');";
         if (!mysql_query($sql,$con))

          {

          die('Error: ' . mysql_error());

          }

        echo "'You have been successfully added.' . '<br>'; "

mysql_close($con);

?>

it gives me this error now: Parse error: syntax error, unexpected 'mysql_close' (T_STRING), expecting ',' or ';' in /opt/lampp/htdocs/project/Newsletter-signup.php on line 38.

Thanks for your help Costantin, my head is exploding.

Mimi
  • 3
  • 5
  • 2
    There's no code here that inserts anything in your database. – binary01 Jan 01 '18 at 10:58
  • mysql is deprected. use mysqli or pdo – rupesh Jan 01 '18 at 11:22
  • i tried changing it in myqli, but it gives me more errors just because there is the i to mysql.:-s – Mimi Jan 01 '18 at 14:30
  • FYI, [you shouldn't use `mysql_*` functions in new code](http://stackoverflow.com/questions/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](http://php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which one is best for you. – John Conde Jan 01 '18 at 15:38

2 Answers2

0

i have xampp on windows with mariadb and mysqli oop so i can't send you a complet script to test but i think you should try this

$sql = "INSERT INTO newsletter (name, email)
  VALUES ('".$_POST[name]."', '".$_POST[email]."')";

or to try this

$sql = "INSERT INTO newsletter (name, email)
  VALUES ('{$_POST[name]}', '{$_POST[email]}')";

these "rooles" ,by experience, you shouldn't avoid in php : 1.you should use {,} more than you expect inside "", 2.you should avoid sending content before a php script part should do something(so the next time you need to add headers or write cookies,sessions,etc.. you will not force to set it in the top of the file and all your code will be compact and easy to view/edit

eg. i use one include file (normal php file:biggest file 2090 lines=63kbytes or minified php file with modules : 3 lines =37 kbytes) and a page for every view in the application/website with a template page as well so you need to centralize and focus all efficiency around a modules you will use in all others pages.

i use oop =i am forced cause xampp put mariadb with php 7 to get the max speed and quality of php execution and i had mysqli driver: i could insert my own function to make conversion mysqli -> mysql user fuctions but i don't need a delay caused by back conversions oop -> structural,so all my code inside modules is oop.

your script should be modified also like this

<?php

//here avoid using of output content or a space before <?php
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
//other stuff

//mysql stuff



?><html>

<body>
<?php
//output here

?>
</body>

</html>

in the past i used cobinations of this 'cause how that guy said mysql is depreceated !

function insert($table){//insert(table,'var1=$val1',"var2=$val2")

    $columns = mysql_query("SHOW COLUMNS FROM "._T($table));
    while ($row = mysql_fetch_assoc($columns)) {
        if((strpos($row['Type'],'char')!==false)or(strpos($row['Type'],'blob')!==false))
            $schema[strtolower($row['Field'])]=true;
        else
            $schema[strtolower($row['Field'])]=false;
    }//$schema

    $na = func_num_args();
    if($na==0 or strpos(func_get_arg(0),'=') !== false)
        die('the table '.$table.'its missing !!!');
    if($na>=2){
        for($k=1;$k<$na;$k++){
            $param_i=func_get_arg($k);
            if(strpos($param_i,'=') !== false){// include all "var=values" for overwrite        
                $temp_para=explode('=', $param_i );
                $params[]=$temp_para[0];
                $values[]=$temp_para[1];
                $matrix[$k]=$schema[$temp_para[0]];//matrix
            }
        }
    }
    $string="INSERT INTO `".$table.'` (';
    $la=count($params);
    $x=1;
    foreach($params as $ch => $vl){
        if($x!=$la)
            $string.='`'.$vl.'`,';
        else
            $string.='`'.$vl.'`';
        $x++;
    }
    $string.=')VALUES (';

    $x=1;
    foreach($values as $ch => $vl){
        if($matrix[$x])
            $tpl="'";
        else
            $tpl="";
        if($x!=$la)
            $string.=$tpl.$vl.$tpl.',';
        else
            $string.=$tpl.$vl.$tpl;
        $x++;
    }
    $string.=');';
    //die
    //print
    //  ($string);
mysql_query($string);
return mysql_insert_id();
}
  • this was the error: Notice: Use of undefined constant name - assumed 'name' in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 Notice: Undefined index: name in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 Notice: Use of undefined constant email - assumed 'email' in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 Notice: Undefined index: email in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 which is VALUES ('".$_POST[name]."', '".$_POST[email]."')"; – Mimi Jan 01 '18 at 11:36
  • try like this mysql_real_escape_string($_POST['name']) and tell us if you got more errors to try something else –  Jan 01 '18 at 11:46
  • adding this, correct me if I did wrong please, I'm new to thi: $sql = "INSERT INTO newsletter (name, email) VALUES (' mysql_real_escape_string($_POST['name'], mysql_real_escape_string($_POST['email'])"; I get the error:Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 – Mimi Jan 01 '18 at 12:12
  • $sql = "INSERT INTO newsletter (name, email) VALUES ('".mysql_real_escape_string($_POST['name'])."','".mysql_real_escape_string($_POST['email'])."');"; and you should check if the table newsletter had name,email WRONG set to other thinks that integers instead strings –  Jan 01 '18 at 12:20
  • in the newsletter table I set the values to both to VARCHAR(45) is this correct? – Mimi Jan 01 '18 at 12:34
  • yes it's is correct ! should be any kind of string,you aren't limited to varchar i use too.for detailes you should check a mysql manual –  Jan 01 '18 at 12:36
  • I corrected the code as you said before, i have this error: syntax error, unexpected 'if' (T_IF) in which is the if after the corrected code on line 28. – Mimi Jan 01 '18 at 12:36
  • edit this post and put here the line with that 'if( ' i use editplus.com to edit so i see lines on the left side of my editor and i can fix quick something. –  Jan 01 '18 at 12:37
0

i put here again that stuff cause there i have no possibility to put from editor code brackets so you may be able to copy paste this stuff correctly :

$sql = "INSERT INTO newsletter (name, email) VALUES ('".mysql_real_escape_string($_POST['name'])."','".mysql_real_escape_string($_POST['email'])."');";

cause php will not tell you you forgot a semi-colon at the end of the previous line but will complain about the 'if' that comes next

anyway how i said in the first post i edited .. is better to use a user function like mine to insert stuff ,to be able to not wrong in critical moments with missing brackets ,...or others errors like this

i never like it when other people gives negatives votes only because something is depreciated ,obsolete but still work and there are servers yet in internet are with old php versions instead of php 7.1 or newest. is the same speech with <noscript></noscript> : if i no using JavaScript you shouldn't deny access to your content cause all your templates are JavaScript and you are not open for alternatives(cause you are not really a programmer) and cause all other "programmers" they doing this


the new answer for copy paste :

echo('You have been successfully added<br>');

echo($sql);die();

         if (!mysql_query($sql,$con))

          {

          die('Error: ' . mysql_error());

          }
  • i cannot answer there ...the script said me : to comment you need 50 points of reputtion! So try this echo('You have been successfully added
    ');
    –  Jan 01 '18 at 13:33
  • same error: Notice: Undefined index: name in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 Notice: Undefined index: email in /opt/lampp/htdocs/project/Newsletter-signup.php on line 27 the script add the row to the database buut it's empty. – Mimi Jan 01 '18 at 13:47
  • well is about something wrong with the table the speech with the iso(i think) to be sure is the table we may check this : echo($sql);die(); if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } AT THIS POINT AFTER FROM THE FORM YOU SEND A NAME AND EMAIL YOU FILL WITH CONTENT THE YOU SHOULD SEE THE RESULT INSERTED IN SQL WE SHOULD EXECUTE ..IF NOT POST ME WHAT ERROR YOU HAVE –  Jan 01 '18 at 13:51
  • @Constantin Like I said, this is not the place to discuss Stack Overflow. https://meta.stackoverflow.com is the place to do that (but take care to do some research before posting there, a lot of questions have already been asked). I am going to clean up this comment thread now. – Modus Tollens Jan 02 '18 at 15:49