2
votes

Code 1:

<?php
class dbConnect {
  var $dbHost = 'localhost',
  $dbUser = 'root',
  $dbPass = '',
  $dbName = 'input_oop',
  $dbTable = 'users';
  function __construct() {

$dbc = mysql_connect($this->dbHost,$this->dbUser,$this->dbPass) or die ("Cannot connect to MySQL : " . mysql_error()); mysql_select_db($this->dbName) or die ("Database not Found : " . mysql_error()); } } class User extends dbConnect { var $name; function userInput($q) { $sql = "INSERT INTO $this->dbTable set name = '".$q."'"; mysql_query($sql) or die (mysql_error()); } } ?>


This is the code to call the class.
<?php
include ('class.php');
$q=$_GET["q"];
$user = new User;
  $user->userInput($q);
?>


Code 2:

<?php
  $q = $_GET['q'];
$dbc=mysql_connect("localhost","root","") or die (mysql_error());
  mysql_select_db('input_oop') or die (mysql_error());
  $sql = "INSERT INTO users set name = '".$q."'";
  mysql_query($sql) or die (mysql_error());
?>

My Code 1 save in my database:
alt text
Saving Multiple!

My Code 2 save in my database:
alt text

What is wrong with my code 1?

3
What do you want it to do in the first place?Jacob Saylor
Besides your actual problem: Please keep in mind to validate every incoming data before sending it to the database. Otherwise your script will be vulnerable for SQL-Injections. Take a look at mysql_real_escape() for example.Ham Vocke♦
How are you calling the userInput() function in Code1?harwig
Can we see more code from your first example?Nathan Osman
look again. I put the code calling the userInput() function.Jorge

3 Answers

5
votes

Well, code 1 is open to SQL injection because you are not escaping $q. As to why you get two records, that problem is not to be found in code 1 but probably in the code that calls userInput.

0
votes

It is very much open to SQL Injections all over, try having a db.php file and just require_once at the start of each php file needing the db.

0
votes

Regarding SQL injection vulnerabilities, I'd suggest using prepared statements with PDO. It's easy to use and extremely secure.

More info: http://php.net/manual/en/pdo.prepared-statements.php