Darial
Darial

Reputation: 33

php function with mysqli

This is my fonction.php :

<?php
function connect(){

$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

                                }

}
?>

But it does not works with my code when I want to call this function :

<?php
include("fonctions.php");
?>


<html>

        <form name="inscription" method="post" action="form.php">
            xxx : <input type="text" name="xxx"/> <br/>
            xxx: <input type="text" name="xxx"<br/>
            <input type="submit" name="valider" value="OK"/>
        </form>

        <?php

        if (isset ($_POST['valider'])){

            $titre=$_POST['xxx'];
            $auteur=$_POST['xxx'];

        connect();

            $sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';



}
        ?>
    </body>
</html>

Before I was using mysql_connect and it was more simple, my fonction was like this :

<?php
function connect(){
    $base = mysql_connect ('localhost', 'root', '');  
    mysql_select_db ('MaBase', $base) ;
}
?>

What is the best way to create a good include with my mysql params ? THanks all for any help.

Upvotes: 0

Views: 1036

Answers (4)

BadPiggie
BadPiggie

Reputation: 6359

It should be,

<?php
function connect(){

$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    return false;
}else{
    return $conn;
}

}
?>

Your query should be,

    <?php

            if (isset($_POST['valider'])){

                $titre=$_POST['xxx'];
                $auteur=$_POST['xxx'];

                $connection = connect();

                if($connection != false){
                $sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
                $result=$connection->query($sql);

                 if($result){ 
                   echo "done"; 
                 }else{
                   echo "faild";
                 }                

                }


          }
   ?>

You should take a tour/learn the basics of OOP

Upvotes: 0

Valmond
Valmond

Reputation: 2969

It seems like all the above answers missed that you have two variables with the same name:

$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';

Both are called $xxx

IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)

Upvotes: -1

Thalinda Bandara
Thalinda Bandara

Reputation: 1079

To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff

database.class.php //databaseconnection

 class DatabaseConnections{
      function connect($databaseNaem){

        try{

          return $connection=mysqli_connect("localhost","user","password",'database');

        }catch(Exception $e){
          echo 'Message:'.$e->getMessage();
        }

      }

      function CloseConnection($dataObject){
        if(mysqli_close($dataObject)){
          return 1;
        }else{
          echo "coudn't Close the Database Connection";
        }
      }



      function convert($connection , $vari){
        return mysqli_real_escape_string($connection,$vari);
      }
    }

     //queryclass
    class Query{


      function queryNoresult($stmt){
        if($stmt->execute()){
          return 1;
        }

      }

      function queryNumOfRows($stmt){
        $stmt->execute();
        $result = $stmt->get_result();
        return mysqli_num_rows($result);
      }


      function QueryResult($stmt){
        $stmt->execute();

        $result = $stmt->get_result();
        return $result;
      }


      function illcallothers($stmt,$callto){
        if($callto == 1){
          return $this->queryNoresult($stmt);
        }if ($callto==2) {
          return $this->queryNumOfRows($stmt);
        }
        if($callto == 3){
          return $this->QueryResult($stmt);
        }

      }
    }

as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters

  1. Created statement
  2. The function number

there 3 option in this

  1. if you call $query->illcallothers($stmt,1) this call the function only for execute best for delete and insert because it's return 1 if it's success

  2. if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while

  3. if you call $query->illcallothers($stmt,3) this will return result set from your query

Now lets go to your problem execution

 //first you have to require the database file

  require_once('database.class.php');

 //Then you have to create object from them

 $mymainObj = new DatabaseConnections();//obj from database

 $connetion = $mymainObj->connect('databasename');//this will return a connection Object
 $stmt = $connection->stmt_init(); //then the statement you need the connection object to this 
 $query = new Query();//object from the query class

    //i am not going to put form part in here it will get messy
      $titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection 

      $auteur=$mymainObj->convert($connection,$_POST['xxx']);

    //now you have create the sql
     $sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing

    if($stmt->prepare($sql)){
       $stmt->bind_param('ss',$title,$author);
    if($query->illcallothers($stmt,1)){
     echo "Query Success";
    }

    }

Upvotes: 1

ivanivan
ivanivan

Reputation: 2215

Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...

You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.

function connect($sql){

For defining it, and then to call it

$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);

You'll also need your function to return some sort of value.

What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)

This is written once, and require_once()'d all across 15 web apps for the college I work at.

Upvotes: 1

Related Questions