0

How can I run the functions save and update? It seems there's no error on my code..but still is not functioning. I need to save and update with the shortest code..thanks!

<?php
$mysqli = new mysqli("localhost","root","","sample_db");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$title = $_POST['title'];
$author = $_POST['author'];
$content = $_POST['content'];
$action = $_POST['action_type'];
$blog_id = $_GET['blog_id'];

function save()
    {
        $insert_query = "INSERT INTO tb_blogs (`title`, `author` , `content`) values ('{$title}','{$author}','{$content}')";
        $mysqli->query($insert_query);
    }

function update()
    {
        $update_query = "UPDATE tb_blogs SET `title` = '{$title}', `author` = '{$author}', `content` = '{$content}' WHERE id = '{$blog_id}'";
        $mysqli->query($update_query);
    }

if(isset($_POST["submit"])) {   
    if($action=='create') {
        save();
    }
    elseif($action=='update') {
        update();
    }
}
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
light
  • 21
  • 7
  • You have to pass the `$mysqli` connection into your functions along with the variables. – Rasclatt Nov 24 '15 at 03:33
  • Are you going to use those functions else where, could just put the two lines in your conditionals.. Also you are open to SQL injections.. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – chris85 Nov 24 '15 at 03:43

1 Answers1

2

I know this has been marked as answered, but I think it's important to show a bind parameter example. This is a bit more complex of a solution, mind you, but it's fairly organized so it should be fairly easy to dissect. Also this is just an example, there are many ways to do this script with bind parameters. The bind parameters in the functions is the most important part really:

/classes/class.DatabaseConfig.php

<?php
// Database configuration meant for connection
class   DatabaseConfig
    {
        private static  $singleton;

        public  function __construct()
            {
                if(empty(self::$singleton))
                    self::$singleton    =   $this;

                return self::$singleton;
            }

        public  function connectMySQLi($host = "localhost", $username = "username", $password = "password", $database = "database")
            {
                // Create connection
                try {
                        $mysqli = new mysqli($host, $username, $password, $database);
                        return $mysqli;
                    } catch (mysqli_sql_exception $e) {
                       // Print real error if admin, or write to
                       // secured log file
                       // throw $e;
                       die("Connection has failed.");
                    }
            }
    }

/classes/class.Db.php

<?php
// Singleton-based class to re-use instantiated resources
class Db
    {
        private static $singleton;

        // Default connection
        public static function mysqli()
            {
                if(empty(self::$singleton)) {
                    $con = new DatabaseConfig();
                    self::$singleton = $con->connectMySQLi();
                }

                return self::$singleton;
            }
    }

/functions/function.save.php

<?php
// I have chosen a singleton, but you can pass your db connection as a 
// second argument like save($array,$mysqli)
function save($settings = false)
    {
        // Because the the class allows for a static variable, you can
        // connect straight in the class without using globals
        $mysqli     =   Db::mysqli();
        // Use bind_param/prepare/execute for safe queries
        $stmt       =   $mysqli->prepare("INSERT INTO `tb_blogs` (`title`, `author` , `content`) values (?,?,?)");
        // You can do checks on these variables to see that they are filled out, I have not though
        $stmt->bind_param("sss",$settings['title'],$settings['author'],$settings['content']);
        $stmt->execute();
    }

/functions/function.update.php

<?php
function update($settings = false)
    {
        $mysqli =   Db::mysqli();
        $stmt   =   $mysqli->prepare("UPDATE `tb_blogs` SET `title` = ?, `author` = ?, `content` = ? WHERE id = ?");
        $stmt->bind_param("sssi",$settings['title'],$settings['author'],$settings['content'],$settings['blog_id']);
        $stmt->execute();
    }

index.php

<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// You can make a similar autoloader-type function as well instead of
/// manually writing a crap-load of includes
include_once("functions/function.save.php");
include_once("functions/function.update.php");

// Do single wrapper for submit
if(isset($_POST['submit'])) {
    // Check for create
    if($_POST["action_type"] =='create')   
        save($_POST);
    // Check for update
    elseif($_POST["action_type"] =='update') 
        update($_POST);
}
Rasclatt
  • 12,498
  • 3
  • 25
  • 33