Example #1
1
 public function processQuery($sql, $type = NULL)
 {
     $result = mysqli_query($this->db, $sql);
     $this->checkForError();
     $data = array();
     if ($result instanceof mysqli_result) {
         $resultType = MYSQLI_NUM;
         if ($type == 'assoc') {
             $resultType = MYSQLI_ASSOC;
         }
         while ($row = mysqli_fetch_array($result, $resultType)) {
             if (mysqli_affected_rows($this->db) > 1) {
                 array_push($data, $row);
             } else {
                 $data = $row;
             }
         }
         mysqli_free_result($result);
     } else {
         if ($result) {
             $data = mysqli_insert_id($this->db);
         }
     }
     return $data;
 }
Example #2
0
 function saveSubrutina($idSubRutina, $Orden, $idRutina, $Nombre)
 {
     // Esta función nos regresa la subrutina de una rutina especifica (dividida por días)
     //Creamos la conexión con la función anterior
     $conexion = obtenerConexion();
     if ($conexion) {
         //Verificamos que la conexión se haya realizado de manera correcta
         mysqli_set_charset($conexion, "utf8");
         //formato de datos utf8
         if ($idSubRutina == NULL or $idSubRutina == 0 or $idSubRutina == '') {
             $sql = "INSERT INTO `Subrutina` (`Orden`, `IdRutina`, `Nombre`) VALUES ('{$Orden}', '{$idRutina}', '{$Nombre}');";
         } else {
             $sql = "UPDATE `Subrutina` SET `Orden`='{$Orden}', `IdRutina`='{$idRutina}', `Nombre`='{$Nombre}' WHERE `SR_ID`='{$idSubRutina}';";
         }
         if ($result = mysqli_query($conexion, $sql)) {
             if ($idSubRutina == NULL or $idSubRutina == 0 or $idSubRutina == '') {
                 $idSubRutina = mysqli_insert_id($conexion);
             }
             $response["subrutina"] = $this->getsubrutinaByIdSubutina($idSubRutina);
             $response["success"] = 0;
             $response["message"] = 'Subrutina guardada correctamente';
         } else {
             $response["success"] = 4;
             $response["message"] = 'Se presentó un error al ejecutar la consulta';
         }
         desconectar($conexion);
         //desconectamos la base de datos
     } else {
         $response["success"] = 3;
         $response["message"] = 'Se presentó un error al realizar la conexión con la base de datos';
     }
     return $response;
     //devolvemos el array
 }
Example #3
0
function venda($conn, $idUsuario, $idCliente)
{
    $data = date('Y-m-d h:m:s');
    $statusVenda = '1';
    /*
        statusVenda (0) =  cancelada
        statusVenda (1) =  aberda
        statusVenda (2) =  concluida
    */
    $sqlVenda = "SELECT * FROM venda WHERE id_usuario='{$idUsuario}' AND id_cliente='{$idCliente}'";
    //
    $sVenda = mysqli_query($conn, $sqlVenda);
    if (!mysqli_num_rows($sVenda)) {
        /* Verificando a existencia dessa venda, relacao funcionario cliente */
        $insert_pedido = "INSERT INTO venda (id_usuario, data, id_cliente, statusVenda) VALUE\n                    ('{$idUsuario}', '{$data}', '{$idCliente}', '{$statusVenda}')";
        mysqli_query($conn, $insert_pedido);
        $idVenda = mysqli_insert_id($conn);
        /* ID referente a esta venda */
    } else {
        /* --- Encontrar o id relacionado a essa venda */
        $sql = "SELECT idVenda FROM venda WHERE id_cliente='{$idCliente}' AND id_usuario='{$idUsuario}'";
        $query = mysqli_query($conn, $sql);
        $getId = mysqli_fetch_array($query);
        $idVenda = $getId['idVenda'];
    }
    return $idVenda;
}
Example #4
0
 public static function queryToArray($sql)
 {
     global $my_user, $my_pass, $my_host, $my_db, $config_enable_cache;
     $link = Database::getLink();
     $db_selected = mysqli_select_db($link, $my_db);
     if (!$db_selected) {
         die('Can\'t use ' . $my_db . ' : ' . mysqli_error($link));
     }
     // Perform Query
     $result = mysqli_query($link, $sql);
     $id = mysqli_insert_id($link);
     if ($id > 0) {
         // we did an insert, just return the id
         return $id;
     }
     //echo ("\ndatabase qtoa before proc id is $id");
     if (!$result) {
         $message = 'Invalid query: ' . mysqli_error($link) . "\n";
         $message .= 'Whole query: ' . $sql;
         die($message);
     }
     if ($result === true) {
         // probably an insert..
         return false;
     }
     $rows = array();
     while ($row = mysqli_fetch_assoc($result)) {
         $rows[] = $row;
     }
     return $rows;
 }
 function read_hotels2()
 {
     global $db;
     $gohar_hotel = array();
     $safar_hotel = array();
     $new_hotel = array();
     $sql = mysqli_query($this->db_gohar, "SELECT `id`,`fa_hotel`,`en_hotel`,`stars` FROM `htl_hotel` ");
     while ($row = mysqli_fetch_assoc($sql)) {
         $gohar_hotel[$row['id']]['name'] = $row['fa_hotel'];
         $gohar_hotel[$row['id']]['en_name'] = $row['en_hotel'];
         $gohar_hotel[$row['id']]['stars'] = $row['stars'];
     }
     echo 'HOTELS COUNT :: ' . count($gohar_hotel) . '<br>';
     foreach ($gohar_hotel as $id => $hotel) {
         //$insert-> execute(array(':name'=>$hotel['name'],':en_name'=>$hotel['en_name'],':star'=>$hotel['stars']));
         $sql = "INSERT INTO `hotels` (`id`, `name`, `en_name`, `star`) VALUES (NULL,'{$hotel['name']}','{$hotel['en_name']}','{$hotel['stars']}');)";
         echo $sql . '<br>';
         mysqli_query($db, $sql);
         $hotels_id = mysqli_insert_id($db);
         $sql = "INSERT INTO hotels_source (`hotels_id`,`source_id`,`name`,`en_name`,`id_source_hotel`) VALUES({$hotels_id},1,'{$hotel['name']}','{$hotel['en_name']}',{$id})";
         echo '<br>' . $sql . '<br>';
         mysqli_query($db, $sql);
         echo $hotels_id . '<br>';
         // echo $insert2->execute(array(':hotels_id'=>$hotels_id,':name'=>$hotel['name'],':en_name'=>$hotel['en_name'],':id_source_hotel'=>$id));
     }
 }
Example #6
0
 /**
  * Storing new user
  * returns user details
  */
 public function storeUser($name, $email, $gcm_regid)
 {
     // insert user into database
     $c = new DB_Connect();
     $d = $c->connect();
     $test = mysqli_query($d, "SELECT * class_details where code='{$email}'");
     if ($test) {
         $result = mysqli_query($d, "INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('{$name}', '{$email}', '{$gcm_regid}', NOW())");
         // check for successful store
         if ($result) {
             // get user details
             $id = mysqli_insert_id();
             // last inserted id
             $result = mysqli_query($d, "SELECT * FROM gcm_users WHERE id = {$id}") or die(mysql_error());
             // return user details
             if (mysqli_num_rows($result) > 0) {
                 return mysqli_fetch_array($result);
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
Example #7
0
function lisa()
{
    // siia on vaja funktsionaalsust (13. nädalal)
    global $connection;
    if (empty($_SESSION["user"])) {
        header("Location: ?page=login");
    } elseif ($_SESSION["roll"] != "admin") {
        header("Location: ?page=loomad");
    } else {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ($_POST["nimi"] == "" || $_POST["puur"] == "") {
                $errors[] = "Nimi või puur on täitmata!";
            } elseif (upload("liik") == "") {
                $errors[] = "Faili saatmine ebaõnnestus";
            } else {
                $nimi = mysqli_real_escape_string($connection, $_POST["nimi"]);
                $puur = mysqli_real_escape_string($connection, $_POST["puur"]);
                $liik = mysqli_real_escape_string($connection, upload("liik"));
                $sql = "INSERT INTO ttilk__loomaaed(nimi, puur, liik) VALUES ('{$nimi}', '{$puur}', '{$liik}')";
                $result = mysqli_query($connection, $sql);
                if (mysqli_insert_id($connection)) {
                    header("Location: ?page=loomad");
                } else {
                    header("Location: ?page=loomavorm");
                }
            }
        }
    }
    include_once 'views/loomavorm.html';
}
Example #8
0
 function update($id, $name)
 {
     $query = "update category set name = '{$this->name}' where id = {$id}";
     $result = mysqli_query(self::$conn, $query);
     //echo $this->name."effected rows = ".$result;
     return mysqli_insert_id(self::$conn);
 }
 public function create($content, Users $user)
 {
     $message = new Messages();
     $valid = $message->setContent($content);
     if ($valid === true) {
         $valid = $message->setUser($user);
         if ($valid === true) {
             $content = mysqli_real_escape_string($this->database, $message->getContent());
             $id_user = $message->getUser();
             $query = "INSERT INTO messages (content, id_user) \n\t\t\t\t\tVALUES ('" . $content . "', '" . $id_user . "')";
             $result = mysqli_query($this->database, $query);
             if ($result) {
                 $id = mysqli_insert_id($this->database);
                 if ($id) {
                     return $this->findById($id);
                 } else {
                     return "Erreur serveur.";
                 }
             } else {
                 return mysqli_error();
             }
         } else {
             return $valid;
         }
     } else {
         return $valid;
     }
 }
 public function __construct($query, $parameters, $resource, $link)
 {
     $this->resource = $resource;
     $this->affected_rows = mysqli_affected_rows($link);
     $this->last_inserted_id = mysqli_insert_id($link);
     parent::__construct($query, $parameters);
 }
Example #11
0
function work($file_name, $connect)
{
    $topic = "myschool";
    $reg_ids = "";
    $title = $_POST['title'];
    $time = date("Y-m-d , H:i:s");
    $query = "INSERT INTO `images`(`title`, `image`, `time`) VALUES ('{$title}', '{$file_name}', '{$time}')";
    $result = mysqli_query($connect, $query);
    if ($result) {
        $pid = mysqli_insert_id($connect);
        $selectQuery = "SELECT * FROM `images` WHERE `sno` = '{$pid}'";
        $selectResult = mysqli_query($connect, $selectQuery);
        if ($selectResult) {
            if ($row = mysqli_fetch_array($selectResult)) {
                $message[] = array("result" => "success", "title" => $title, "image" => $file_name, "date" => $row['time']);
                $messages = array('image' => $message);
                // TODO uncomment send_push_notification() to send message to devices
                //var_dump($messages);
                echo "<br><br>" . json_encode($messages) . "<br><br><br> Add more images if you want.<br>";
                send_push_notification($reg_ids, json_encode($messages), $topic);
            }
        }
    } else {
        echo "<br>Error";
    }
}
Example #12
0
function add_bd($name, $description, $category, $select)
{
    require "configSQL.php";
    if ($category == "Transport") {
        $cat = "1";
    } else {
        if ($category == "Food") {
            $cat = "2";
        } else {
            $cat = "3";
        }
    }
    //ajout de l'appli
    $req = "INSERT INTO appli (name, description, category) VALUES ('" . $name . "','" . $description . "','" . $cat . "')";
    if (mysqli_query($link, $req)) {
        //récup de l'id appli
        $idAppli = mysqli_insert_id($link);
        //récup de l'id pays
        $slct = "SELECT * FROM countries WHERE name='%s'";
        $req2 = sprintf($slct, $select);
        $res2 = mysqli_query($link, $req2) or die(utf8_encode("request error : ") . $req2);
        $data = mysqli_fetch_array($res2, MYSQLI_ASSOC);
        $idCountry = $data["id"];
        //ajout dans table appli par pays
        $req3 = "INSERT INTO applibycountry (idCountry, idAppli) VALUES ('" . $idCountry . "','" . $idAppli . "')";
        if (mysqli_query($link, $req3)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Example #13
0
 /**
  * Save or update the item data in database
  */
 function save()
 {
     $class = get_called_class();
     $query = "INSERT INTO " . static::$tableName . " (" . implode(",", array_keys($this->columns)) . ") VALUES(";
     $keys = array();
     $values = array();
     foreach ($this->columns as $key => $value) {
         //  $keys[":".$key] = $value;
         $values["'" . $value . "'"] = $value;
     }
     $query .= implode(",", array_keys($values)) . ")";
     if (!($stmt = $this->conn->prepare($query))) {
         echo 'Error: ' . $this->conn->error;
         return false;
         // throw exception, die(), exit, whatever...
     } else {
         $result = $stmt->execute();
         $stmt->close();
     }
     if ($result) {
         //echo '1';
         return mysqli_insert_id($this->conn);
     } else {
         // Failed to insert record
         //echo '2';
         return -1;
         // return 'USER_CREATE_FAILED';
     }
 }
function executeInsertQuery($link, $query)
{
    if (!mysqli_query($link, $query)) {
        echo "Row doesn't work: SQL ['{$query}']";
    }
    return mysqli_insert_id($link);
}
Example #15
0
function clone_table($controller_dblink, $storage_dblink, $table_details, $target_details)
{
    # Setting the cloned table settings
    $table_id = $table_details['id'];
    unset($table_details['id'], $table_details['rows'], $table_details['size'], $table_details['partitions']);
    $table_details['name'] = $target_details->name;
    $table_details['alias'] = $target_details->alias;
    $table_details['environment'] = $target_details->environment;
    # Adding our cloned table settings
    $columns = [];
    foreach ($table_details as $key => $value) {
        $columns[] = "`" . $key . "`='" . mysqli_escape_string($controller_dblink, $value) . "'";
    }
    $query = "\tINSERT INTO\n\t\t\t\t\t" . NQ_TABLE_SETTINGS_TABLE . "\n\t\t\t\tSET\n\t\t\t\t\t" . implode(',', $columns);
    mysqli_sub_query($controller_dblink, $query);
    $new_table_id = mysqli_insert_id($controller_dblink);
    # Cloning the table structure
    $query = "\tCREATE TABLE \n\t\t\t\t\t" . NQ_DATABASE_STORAGE_DATABASE . ".`" . NQ_DATABASE_STRUCTURE_PREFIX . $table_details['app_id'] . '_' . $new_table_id . "`\n\t\t\t\tLIKE\n\t\t\t\t\t" . NQ_DATABASE_STORAGE_DATABASE . ".`" . NQ_DATABASE_STRUCTURE_PREFIX . $table_details['app_id'] . '_' . $table_id . "`";
    mysqli_sub_query($storage_dblink, $query);
    # Copying table links based on table_id
    $query = "\tINSERT INTO\n\t\t\t\t\t" . NQ_TABLE_LINKS_TABLE . "\n\t\t\t\t\t(\n\t\t\t\t\t\t`app_id`,\n\t\t\t\t\t\t`table_id`,\n\t\t\t\t\t\t`link_table_id`,\n\t\t\t\t\t\t`name`,\n\t\t\t\t\t\t`column`,\n\t\t\t\t\t\t`type`\n\t\t\t\t\t)\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t`app_id`,\n\t\t\t\t\t\t" . $new_table_id . ",\n\t\t\t\t\t\t`link_table_id`,\n\t\t\t\t\t\t`name`,\n\t\t\t\t\t\t`column`,\n\t\t\t\t\t\t`type`\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . NQ_TABLE_LINKS_TABLE . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t`table_id` = " . $table_id;
    mysqli_sub_query($controller_dblink, $query);
    # Copying table links based on link_table_id
    $query = "\tINSERT INTO\n\t\t\t\t\t" . NQ_TABLE_LINKS_TABLE . "\n\t\t\t\t\t(\n\t\t\t\t\t\t`app_id`,\n\t\t\t\t\t\t`table_id`,\n\t\t\t\t\t\t`link_table_id`,\n\t\t\t\t\t\t`name`,\n\t\t\t\t\t\t`column`,\n\t\t\t\t\t\t`type`\n\t\t\t\t\t)\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t`app_id`,\n\t\t\t\t\t\t`table_id`,\n\t\t\t\t\t\t" . $new_table_id . ",\n\t\t\t\t\t\t`name`,\n\t\t\t\t\t\t`column`,\n\t\t\t\t\t\t`type`\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . NQ_TABLE_LINKS_TABLE . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t`link_table_id` = " . $table_id;
    mysqli_sub_query($controller_dblink, $query);
    # Returning the table data
    return true;
}
 function addApplicant(Applicant $applicant)
 {
     $connectionObject = Connection::getInstance();
     $connection = $connectionObject->get_connection();
     $name_in_full = $applicant->getNameInFull();
     $name_with_initials = $applicant->getNameWithInitials();
     $nic = $applicant->getNic();
     $is_sri_lankan = $applicant->getIsSriLankan();
     $religion = $applicant->getReligion();
     $address = $applicant->getAddress();
     $telephone = $applicant->getTelephone();
     $district = $applicant->getDistrict();
     $divisional_sec_area = $applicant->getDivisionalSecArea();
     $grama_niladari_divi = $applicant->getGramaNiladariDivi();
     $sql = "SELECT \tapplicant_id FROM applicant WHERE nic = '" . $nic . "'";
     $resultset = mysqli_query($connection, $sql);
     $numberOfRows = mysqli_num_rows($resultset);
     if ($numberOfRows > 0) {
         $row = mysqli_fetch_row($resultset);
         $applicant_id = $row[0];
     } else {
         $stmt = $connection->prepare("INSERT INTO applicant (name_in_full, name_with_initials, nic, religion, address, is_sri_lankan, district, divisional_sec_area, grama_niladari_divi,telephone) VALUES (?,?,?,?,?,?,?,?,?,?)");
         $stmt->bind_param("ssssssssss", $name_in_full, $name_with_initials, $nic, $religion, $address, $is_sri_lankan, $district, $divisional_sec_area, $grama_niladari_divi, $telephone);
         $result = $stmt->execute();
         $stmt->close();
         $applicant_id = mysqli_insert_id($connection);
     }
     return $applicant_id;
 }
Example #17
0
function work($file_name, $connect)
{
    $topic = "myschool";
    $reg_ids = "";
    $title = $_POST['title'];
    $name = $_POST['name'];
    $description = $_POST['message'];
    $url = "";
    if (isset($_POST['url'])) {
        $url = $_POST['url'];
    }
    $time = date("Y-m-d , H:i:s");
    $query = "INSERT INTO `posts`(`title`, `description`, `name`, `image`, `url`, `time`) VALUES ('{$title}', '{$description}', '{$name}', '{$file_name}', '{$url}', '{$time}')";
    $result = mysqli_query($connect, $query);
    if ($result) {
        $pid = mysqli_insert_id($connect);
        $selectQuery = "SELECT * FROM `posts` WHERE `pid` = '{$pid}'";
        $selectResult = mysqli_query($connect, $selectQuery);
        if ($selectResult) {
            if ($row = mysqli_fetch_array($selectResult)) {
                $message[] = array("message" => $description, "name" => $name, "title" => $title, "image" => $file_name, "date" => $row['time'], "url" => $url);
                $messages = array('post' => $message);
                // TODO uncomment send_push_notification() to send message to devices
                //var_dump($messages);
                //echo "<br>".json_encode($messages);
                echo send_push_notification($reg_ids, json_encode($messages), $topic);
            }
        }
    } else {
        echo json_encode(array('result' => "failure", 'response' => "Something went wrong."));
    }
}
Example #18
0
function putRecipe($recipe)
{
    //gets connection and database
    require 'connect.php';
    if (isset($recipe['recipeTitle'], $recipe['type'], $recipe['description'])) {
        $title = trim($recipe['recipeTitle']);
        //removes whitespace before and after
        $type = $recipe['type'];
        $description = $recipe['description'];
        $slug = $recipe['slug'];
        //-----Recipe------
        //"recipe" handles basic information
        $query = "UPDATE recipe SET title = '{$title}', type = '{$type}', description = '{$description}'\n\t\tWHERE slug = '{$slug}'";
        if (mysqli_query($conn, $query)) {
            //$response =  json_decode($slug);
            //echo($response);
            $recipe['recipeId'] = mysqli_insert_id($conn);
            //Need to be stored for later
            echo json_encode($recipe);
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    } else {
        echo "Missing data";
    }
}
Example #19
0
 function insert()
 {
     $query = "insert into orders(order_des,user_id,total_price ,num_items,pid) values('{$this->desc}','{$this->user_id}','{$this->total_price}','{$this->num_items}','{$this->pid}')";
     // adding order sub quantity product
     $result = mysqli_query(self::$conn, $query);
     return mysqli_insert_id(self::$conn);
 }
Example #20
0
 /**
  * Validates, creates a new user (across 2 tables) and login in
  * @param $details
  * @param $login
  * @return string
  */
 public function createNewUser($details, $login)
 {
     $ret = '';
     if (!preg_match("/^[a-zA-Z]+\$/", $details[0]['value'])) {
         $ret = 'Bad first name format';
         return $ret;
     }
     if (!preg_match("/^[a-zA-Z]+\$/", $details[1]['value'])) {
         $ret = 'Bad last name format';
         return $ret;
     }
     if (!filter_var($details[2]['value'], FILTER_VALIDATE_EMAIL)) {
         $ret = 'Bad email format';
         return $ret;
     }
     if ($details[3]['value'] !== $details[4]['value']) {
         $ret = 'Passwords do not match';
         return $ret;
     }
     $this->_db->query("INSERT INTO " . TBL_USERS . " (user_email, user_password) VALUES ('" . $details[2]['value'] . "', '" . md5($details[3]['value']) . "')");
     $user_id = mysqli_insert_id($this->_db);
     $this->_db->query("INSERT INTO " . TBL_USERS_INFO . " (user_id, user_firstname, user_lastname, user_created)" . " VALUES (" . $user_id . ", '" . $details[0]['value'] . "', '" . $details[1]['value'] . "', '" . date('Y-m-d H:i:s') . "')");
     if (mysqli_errno($this->_db) === 1062) {
         $ret = 'This email is already taken';
     }
     if (!$ret) {
         $login->fillSession($this->getUserById($user_id));
     }
     return $ret;
 }
Example #21
0
 public function addUpdate($title, $body, $target, $source)
 {
     $con = $this->connect();
     $title = mysqli_real_escape_string($con, $title);
     $body = mysqli_real_escape_string($con, $body);
     $target = mysqli_real_escape_string($con, $target);
     $source = mysqli_real_escape_string($con, $source);
     $query = "INSERT INTO news VALUES(null, '{$title}', '{$body}','{$target}', NOW(),'{$source}')";
     $res = mysqli_query($con, $query) or die("Couldn't execute query: " . mysqli_error($con));
     if ($res) {
         $id = mysqli_insert_id($con);
         $query = "SELECT * FROM news WHERE id = {$id}";
         $update = mysqli_query($con, $query);
         if (mysqli_num_rows($update) > 0) {
             $rows = array();
             while ($row = mysqli_fetch_array($update, MYSQLI_ASSOC)) {
                 $rows[] = $row;
             }
             return $rows;
         } else {
             return false;
         }
     } else {
         return false;
     }
     $this->close();
 }
Example #22
0
function addUser($dbConn, $username, $password, $email)
{
    // Add user to USERS table.
    $dbQuery = "INSERT INTO USERS(Username, First_name, Last_name, Email, Status, About, Date_joined, Password) " . "VALUES('" . $username . "', '', '', '" . $email . "', 'active', '', CURDATE(), '" . $password . "')";
    FB::info('addUser() query:' . $dbQuery);
    if ($dbResults = mysqli_query($dbConn, $dbQuery)) {
        FB::log('USERS insert success! (I think)');
    } else {
        FB::error('USERS insert failed!');
    }
    $userId = mysqli_insert_id($dbConn);
    // ID of the latest created user.
    FB::info('New User ID: ' . $userId);
    // Add user role for newly created user into USER_ROLES table.
    $dbQuery = "INSERT INTO USER_ROLES(User_Id, Role_Id)" . "VALUES(" . $userId . ", 1)";
    if ($dbResults = mysqli_query($dbConn, $dbQuery)) {
        FB::log('USER_ROLES insert success! (I think)');
    } else {
        FB::error('USER_ROLES insert failed!');
    }
    // Add default avatar for newly created user into IMAGES table.
    $avatar = file('images/default_avatar.png');
    // Default avatar for new users.
    $dbQuery = "INSERT INTO IMAGES(Description, Image, User_Id) " . "VALUES('test', '" . $avatar . "', " . $userId . ")";
    if ($dbResults = mysqli_query($dbConn, $dbQuery)) {
        FB::log('IMAGES insert success! (I think)');
    } else {
        FB::error('IMAGES insert failed!');
    }
}
Example #23
0
/**
* raw mysql query
* @param $WantRC - if 1
* @param $WantLID - if 1
* @param $rtnRC - return row count
* @param $rtnLID - return Last ID
* @returns result
*
* example
fun_SQLQuery($query, $WantRC=0, $WantLID=0, $rtnRC="", $rtnLID="", $OtherDBConn="", $arVar="");
*/
function fun_SQLQuery($query, $WantRC = 0, $WantLID = 0, &$rtnRC = "", &$rtnLID = "", $OtherDBConn = "", $arVar = "")
{
    global $conn;
    //debug
    //echo "fun_SQLQuery:($query)\n";
    if ($query) {
        // 		if (($results = $conn->query($query,MYSQLI_USE_RESULT)) === false)
        // 		{
        // 			printf("Error: %s : $query\n", $conn->error);
        // 		}
        $result = mysqli_query($conn, $query) or die("Select Query failed : " . mysqli_error() . " :<br>\r\n {$query}");
        if ($WantLID == 1) {
            //$rtnLID = $conn->insert_id;
            $rtnLID = mysqli_insert_id($conn);
        } else {
            $rtnLID = "";
        }
        if ($WantRC == 1) {
            //$rtnRC = $result->num_rows;
            $rtnRC = mysqli_num_rows($result);
        } else {
            $rtnRC = "";
        }
        unset($arVar);
        //debug
        //var_dump($result);
        return $result;
    }
    unset($arVar);
    return "fun_SQLQuery: No Query\n";
}
Example #24
0
function create()
{
    global $link;
    foreach ($_POST as $name => $value) {
        ${$name} = mysqli_real_escape_string($link, $value);
    }
    $sql2 = "INSERT INTO address (Street, City, State, Zip) VALUES ('{$Street}', '{$City}', '{$State}', '{$Zip}')";
    $sql0 = "SELECT Address_ID FROM address WHERE Street='{$Street}' AND City='{$City}' AND State='{$State}' AND Zip='{$Zip}'";
    //determine if address existing
    $results = $link->query($sql0);
    if ($results->num_rows > 0) {
        $row = $results->fetch_assoc();
        $addressID = $row['Address_ID'];
    } else {
        if (mysqli_query($link, $sql2)) {
            echo "Address added successfully.";
        } else {
            echo "ERROR: Was not able to execute {$sql2}. " . mysqli_error($link);
        }
        $addressID = mysqli_insert_id($link);
    }
    $sql = "INSERT INTO contacts (FirstName, LastName, Address_ID) VALUES ('{$FirstName}', '{$LastName}', {$addressID})";
    //add contact
    if (mysqli_query($link, $sql)) {
        echo "Contact added successfully.";
    } else {
        echo "ERROR: Was not able to execute {$sql}. " . mysqli_error($link);
    }
}
Example #25
0
 public function ajouter($value, $debug = false)
 {
     $this->dbConnect();
     $this->begin();
     try {
         $value['defaut'] == 'oui' ? $defaut = "oui" : ($defaut = "non");
         $sql = "INSERT INTO `product_image`\n\t\t\t\t( `num_produit`, `fichier`, `defaut` )\n\t\t\t\tVALUES (\n\t\t\t\t" . intval($value["num_produit"]) . ",\n\t\t\t\t'" . addslashes($value["fichier"]) . "',\n\t\t\t\t'" . $defaut . "'\n\t\t\t);";
         if ($debug) {
             echo $sql . "<br>";
         } else {
             $result = mysqli_query($this->mysqli, $sql);
             if (!$result) {
                 throw new Exception($sql);
             }
             $id_record = mysqli_insert_id($this->mysqli);
         }
         $this->commit();
     } catch (Exception $e) {
         $this->rollback();
         throw new Exception("Erreur Mysql " . $e->getMessage());
         return "errrrrrrooooOOor";
     }
     $this->dbDisConnect();
     return $id_record;
 }
/**
* добавление комментария
**/
function add_comment()
{
    global $connection;
    $comment_author = trim(mysqli_real_escape_string($connection, $_POST['commentAuthor']));
    $comment_text = trim(mysqli_real_escape_string($connection, $_POST['commentText']));
    $parent = (int) $_POST['parent'];
    $comment_product = (int) $_POST['productId'];
    $is_admin = isset($_SESSION['auth']['is_admin']) ? $_SESSION['auth']['is_admin'] : 0;
    // если нет ID товара
    if (!$comment_product) {
        $res = array('answer' => 'Неизвестный продукт!');
        return json_encode($res);
    }
    // если не заполнены поля
    if (empty($comment_author) or empty($comment_text)) {
        $res = array('answer' => 'Все поля обязательны к заполнению');
        return json_encode($res);
    }
    $query = "INSERT INTO comments (comment_author, comment_text, parent, comment_product, is_admin)\n\t\t\t\tVALUES ('{$comment_author}', '{$comment_text}', {$parent}, {$comment_product}, {$is_admin})";
    $res = mysqli_query($connection, $query);
    if (mysqli_affected_rows($connection) > 0) {
        $comment_id = mysqli_insert_id($connection);
        $comment_html = get_last_comment($comment_id);
        return $comment_html;
    } else {
        $res = array('answer' => 'Ошибка добавления комментария');
        return json_encode($res);
    }
}
Example #27
0
function DetailsInsert($con)
{
    $datecon = $_POST["YYYY"] . "-" . $_POST["MM"] . "-" . $_POST["DD"];
    //$query="INSERT into customers ('check_in', 'check-out', 'room_type', 'adults_per_room', 'children_0_5', 'children_6_12') VALUES ('$checkin.','$checkout','$roomtype','$adults','$child0','$child6');";
    $query = "INSERT INTO `happy_hearts`.`schoolinfo` ( `school_id`, `date_updated`, `children`, `teachers`,`girls`,`boys`,`new_enroll`,`no_left`) VALUES ('" . $_POST["school_id"] . "','" . $_POST["udate"] . "','" . $_POST["children"] . "','" . $_POST["girls"] . "','" . $_POST["boys"] . "','" . $_POST["no_enroll"] . "','" . $_POST["no_left"] . "');";
    //id is auto increment
    echo $query;
    if (mysqli_query($con, $query)) {
        $id = mysqli_insert_id($con);
        //Gives the auto generated id required in employee_master table
    } else {
        return false;
    }
    /*$query1="insert into employee_master(emp_id,emp_username,emp_password) values(".$id.",'".$_POST["user"]."','".$_POST["pass"]."');";	//id is auto increment,we take auto incremented id from the first table to put in employee id in employee_master table and this query stores the username and password from the query  
    
    
    	echo $query1; //see screenshot
    
    
    	if(!mysqli_query($con,$query1)) //Runs the query and returns boolean variable.
    	{
    		return false;
    	}
    	else 
    	{
    		return true;
    	}	//checks the second query just as the first
    	*/
}
Example #28
0
 /**
  * Save laps data into database.
  */
 public function algorithm($data, $parent_id)
 {
     $db = \utils\DB\Database::getInstance();
     $conn = $db->getConnection();
     $ids = array();
     foreach ($data as $lap) {
         $lap = $lap->getVars();
         if ($stmt = $conn->prepare("INSERT INTO `gps_db`.`activityLap_t` (`StartTime`, `TotalTimeSeconds`, `DistanceMeters`, `MaximumSpeed`, `Calories`, `AverageHeartRateBpm`, `MaximumHeartRateBpm`, `Intensity`, `Cadence`, `TriggerMethod`, `Activity`, `Notes`)\n\t\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
             $stmt->bind_param("sdddiiiiiiis", $StartTime, $TotalTime, $Distance, $MaxSpeed, $Calories, $AvgHR, $MaxHR, $Intensity, $Cadence, $TriggerMethod, $Activity, $Notes);
             $StartTime = $lap["StartTime"]->format("Y-m-d\\TH:i:sT");
             $TotalTime = $lap["TotalTimeSeconds"];
             $Distance = $lap["DistanceMeters"];
             $MaxSpeed = $lap["MaximumSpeed"];
             $Calories = $lap["Calories"];
             $AvgHR = $lap["AverageHeartRateBpm"];
             $MaxHR = $lap["MaximumHeartRateBpm"];
             $Intensity = strtolower($lap["Intensity"]) == "resting" ? 2 : 1;
             $Cadence = $lap["Cadence"];
             $TriggerMethod = $this->triggerID($lap["TriggerMethod"]);
             $Activity = $parent_id !== NULL ? $parent_id : "1";
             $Notes = $lap["Notes"];
             if ($stmt->execute() === FALSE) {
                 die("Error: " . $stmt->error);
             } else {
                 array_push($ids, mysqli_insert_id($conn));
             }
         }
     }
     $stmt->close();
     return $ids;
 }
Example #29
0
function dbInsert($data, $table)
{
    global $fullSql, $database_link;
    global $db_stats;
    // the following block swaps the parameters if they were given in the wrong order.
    // it allows the method to work for those that would rather it (or expect it to)
    // follow closer with SQL convention:
    // insert into the TABLE this DATA
    if (is_string($data) && is_array($table)) {
        $tmp = $data;
        $data = $table;
        $table = $tmp;
        // trigger_error('QDB - Parameters passed to insert() were in reverse order, but it has been allowed', E_USER_NOTICE);
    }
    $sql = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($data)) . '`)  VALUES (' . implode(',', dbPlaceHolders($data)) . ')';
    $time_start = microtime(true);
    dbBeginTransaction();
    $result = dbQuery($sql, $data);
    if ($result) {
        $id = mysqli_insert_id($database_link);
        dbCommitTransaction();
        // return $id;
    } else {
        if ($table != 'Contact') {
            trigger_error('QDB - Insert failed.', E_USER_WARNING);
        }
        dbRollbackTransaction();
        // $id = false;
    }
    // logfile($fullSql);
    $time_end = microtime(true);
    $db_stats['insert_sec'] += number_format($time_end - $time_start, 8);
    $db_stats['insert']++;
    return $id;
}
 /**
  * Native function for executing mysql query
  */
 private function executeQuery($q)
 {
     if (empty($q)) {
         throw new DBException('Empty query submitted!');
     }
     if (DB_DEBUG) {
         $start = microtime(true);
     }
     $this->_res_resource = mysqli_query($this->_con, $q);
     if (DB_DEBUG) {
         $end = microtime(true);
         $this->_executedQueries[] = array('q' => $q, 'time' => $end - $start);
     }
     if (!$this->_res_resource) {
         throw new DBException(mysqli_error($this->_con));
     }
     if (preg_match('/^SELECT.+/', strtoupper($q))) {
         $this->_res_num = @mysqli_num_rows($this->_res_resource);
     } elseif (preg_match('/^INSERT.+/', strtoupper($q))) {
         $this->_last_inserted_id = mysqli_insert_id($this->_con);
         $this->_affected_rows = @mysqli_affected_rows($this->_con);
     } else {
         $this->_affected_rows = @mysqli_affected_rows($this->_con);
     }
     return true;
 }