Hi I'm trying to update my tbl_jadwal, it said success, but database is not updated, anybody can please help me finding where the problem is ? Thankyou
<?php
if (isset($_GET['id'])) {
$ID = $_GET['id'];
} else {
$ID = "";
}
// create array variable to store category data
$category_data = array();
$sql_query = "SELECT Category_ID, Category_name
FROM tbl_category
ORDER BY Category_ID ASC";
$stmt_category = $connect->stmt_init();
if ($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['Category_ID'],
$category_data['Category_name']
);
}
$sql_query = "SELECT Menu_image FROM tbl_jadwal WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($previous_menu_image);
$stmt->fetch();
$stmt->close();
}
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->fetch();
$stmt->close();
}
if (isset($_POST['btnEdit'])) {
$nama_lokasi = $_POST['nama_lokasi'];
$category_ID = $_POST['category_ID'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$description = $_POST['description'];
// get image info
$menu_image = $_FILES['menu_image']['name'];
$image_error = $_FILES['menu_image']['error'];
$image_type = $_FILES['menu_image']['type'];
// create array variable to handle error
$error = array();
// updating all data
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?, Latitude = ?, Longitude = ?, Phone = ?, Email = ?, Menu_image = ?, Description = ?
WHERE Menu_ID = ?";
$upload_image = 'upload/images/' . $menu_image;
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ssssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
} else {
updating all data except image file
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?,
Longitude = ?, Latitude = ?, Phone = ?, Email = ?, Description = ?
WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
}
check update result
if ($update_result) {
$error['update_data'] = " <span class='label label-primary'>Success update</span>";
} else {
$error['update_data'] = " <span class='label label-danger'>failed update</span>";
}
This my database structure
replace bind_param() with bindParam(':data', $data);
or try $stmt->execute(array(':data' => $data))
Hi Just write the simple query firstly and add EXPLAIN before it.
For example:
EXPLAIN update table set name='test' where id=1;
This statement will show all the possible error. In this way you will be able to resolve the problem.
Related
I am trying to get data from ajax response as json. But I am getting error response. I had this problem once, and i manage to solve it by adding header('Content-type: application/json'); to my php file. But if I do it now it kind of break my code, because i am including the file to another file that has a lot of html code in it and it loads the code in response. Can i get json response without that header somehow ?
$('#catlist').change(function() {
var opt = $(this).val();
console.log(opt);
$.ajax({
url: 'includes/processproducts.php',
type: 'get',
dataType: "json",
data: {opt: opt},
success: function(options){
console.log(options);
},
error: function(options){
console.log(options);
console.log("not working");
}
});
$('#brandlist').attr('disabled', false);
});
<?php
if(!isset($_SESSION)){
session_start();
}
//
include '../../core/initialize.php';
/*
include 'includes/head.php';
include 'includes/navigation.php';
include 'includes/functions.php';
*/
$sql = "SELECT * FROM product";
$result = $db->query($sql);
if(isset($_REQUEST['submitbtn'])){
if(isset($_REQUEST['edit'])){
?>
<script> alert("EDIT") </script>
<?php
if(!empty($_POST['handleName'])){
$nameEdVar = $_POST['handleName'];
} else {
$nameEdVar = NULL;
}
if(!empty($_POST['handleCat'])){
$catEdVar = $_POST['handleCat'];
} else {
$catEdVar = NULL;
}
if(!empty($_POST['handleBrand'])){
$brandEdVar = $_POST['handleBrand'];
} else {
$brandEdVar = NULL;
}
if(!empty($_POST['handleDesc'])){
$descEdVar = $_POST['handleDesc'];
} else {
$descEdVar = NULL;
}
if(!($_FILES['image']['size'] == 0)){
$path = processImg($_REQUEST['edit']);
} else {
$path = NULL;
}
//$path = NULL;
$edit_id = (int)$_REQUEST['edit'];
$sqled = "UPDATE product SET name='$nameEdVar', cat_id='$catEdVar', brand_id='$brandEdVar', image='$path', description='$descEdVar' WHERE product.id_P = $edit_id";
$db->query($sqled);
//header('Location: products.php');
}else{
if(($_POST['handleName'] =='') || ($_POST['handleCat'] == '')
|| ($_POST['handleBrand'] == '') || ($_POST['handleDesc'] == '')
|| ($_FILES['image']['size'] == 0)){ ?>
<script> alert('ADD časť niečo nevyplnene'); </script>
<?php
}else{
?> <script> alert('ADD časť všetko vyplnene'); </script>
<?php
$nameVar = $_POST['handleName'];
$catVar = $_POST['handleCat'];
$brandVar = $_POST['handleBrand'];
$descVar = $_POST['handleDesc'];
$qVar = 1;
//$path = "https://localhost/shop/imgs/31.jpg";
$sql = "SELECT MAX(id_p) FROM product";
$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bind_result($maxid);
$stmt->fetch();
$path = processImg(++$maxid);
$stmt->close();
$sql = "INSERT INTO product (id_p, name, cat_id, brand_id, image, description, quantity) VALUES(?, ?, ?, ?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param('sssssss', $nullvar = NULL, $nameVar, $catVar, $brandVar, $path, $descVar, $qVar);
$stmt->execute();
$stmt->close();
//header('Location: products.php');
}
}
}
//Delete Product
if(isset($_GET['delete']) && !empty($_GET['delete'])){
$delete_id = (int)$_GET['delete'];
$sqldel = "DELETE FROM product WHERE product.id_p = $delete_id";
$stmt = $db->prepare($sqldel);
$stmt->execute();
$stmt->close();
header('Location: products.php');
}
if(isset($_REQUEST['edit'])){
echo "
<script>
$(document).ready(function() {
$('#addBox').modal('show');
})
</script>";
}
$sqlcat = "SELECT * FROM category";
$stmtcat = $db->prepare($sqlcat);
$stmtcat->execute();
$stmtcat->bind_result($cat_id, $type);
$stmtcat->store_result();
$cat = array();
while($stmtcat->fetch()){
$cat[$cat_id] = array();
$cat[$cat_id]["type"] = $type;
}
$stmtcat->close();
$sqlbrand = "SELECT * FROM brand";
$stmtbrand = $db->prepare($sqlbrand);
$stmtbrand->execute();
$stmtbrand->bind_result($brand_id, $name);
$stmtbrand->store_result();
$brand = array();
while($stmtbrand->fetch()){
$brand[$brand_id] = array();
$brand[$brand_id]["name"] = $name;
}
$stmtbrand->close();
if(isset($_REQUEST['submitcategory'])){
$sql = "INSERT INTO category (cat_id, type) VALUES(?, ?) ON DUPLICATE KEY UPDATE cat_id = cat_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('is', $cat_id = NULL, $_REQUEST['category']);
$stmt->execute();
$stmt->close();
foreach ($_REQUEST as $key=>$value){if($key != "category" && $value != "Submit"){
if($value == ""){
exit();
}
var_dump($value);
$sql = "INSERT INTO brand(brand_id, NAME) VALUES(?, ?) ON DUPLICATE KEY UPDATE brand_id = brand_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('is', $brand_id = NULL, $value);
$stmt->execute();
$stmt->close();
$sql = "SELECT brand_id, cat_id FROM brand,category WHERE brand.name= ? AND category.type = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $value, $_REQUEST['category']);
$stmt->execute();
$stmt->bind_result($brand_id, $cat_id);
$stmt->fetch();
$stmt->close();
$sql = "INSERT INTO brand_category(brand_id, cat_id) VALUES(?, ?) ON DUPLICATE KEY UPDATE brand_id = brand_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $brand_id, $cat_id );
$stmt->execute();
$stmt->close();
}
}
}elseif(isset($_REQUEST['submitbrand'])){
$sql = "INSERT INTO brand (brand_id, name) VALUES(?, ?) ON DUPLICATE KEY UPDATE brand_id = brand_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('is', $brand_id = NULL, $_REQUEST['brand']);
$stmt->execute();
$stmt->close();
foreach ($_REQUEST as $key=>$value){if($key != "brand" && $value != "Submit"){
if($value == ""){
exit();
}
$sql = "INSERT INTO category (cat_id, type) VALUES(?, ?) ON DUPLICATE KEY UPDATE cat_id = cat_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('is', $cat_id = NULL, $value);
$stmt->execute();
$stmt->close();
$sql = "SELECT brand_id, cat_id FROM brand,category WHERE brand.name= ? AND category.type = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $_REQUEST['brand'], $value);
$stmt->execute();
$stmt->bind_result($brand_id, $cat_id);
$stmt->fetch();
$stmt->close();
$sql = "INSERT INTO brand_category(brand_id, cat_id) VALUES(?, ?) ON DUPLICATE KEY UPDATE brand_id = brand_id";
$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $brand_id, $cat_id );
$stmt->execute();
$stmt->close();
}
}
}
$sql = "SELECT brand.name, brand.brand_id FROM brand JOIN brand_category ON brand_category.brand_id = brand.brand_id WHERE brand_category.cat_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $_REQUEST['opt']);
$stmt->execute();
$stmt->bind_result($name, $brand_id);
$stmt->store_result();
$options = array();
echo $name;
echo $brand_id;
while($stmt->fetch()){
$options[$brand_id] = array();
$options[$brand_id]["name"] = $name;
}
//header('Content-type: application/json');
echo json_encode($options);
$stmt->close();
?>
Remove the following line from your ajax call:
dataType: "json"
and change the line
success: function(options){
var data = JSON.parse(options); // convert the json to js array and use it
}
Try this, it will work
Solved it by creating file just for ajax call.
I am using Opencart v2.2.0 and I am having problem with my php script. The line in question is:
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
The whole function including the line above is as follows:
function restoreBackup()
{
global $mysqli;
$i = 0;
$getpic = "SELECT * FROM oc_product_backup LIMIT 0, 100000";
$backup = $mysqli->query($getpic);
$mysqli->autocommit(FALSE);
$updateproduct_sql = "UPDATE oc_product SET image = ?, ean = ?, model = ?, status = ?, price_sync = ?, modified_by = ?, date_modified = ? WHERE product_id= ?";
$updatedescription_sql = "UPDATE oc_product_description SET name = ?, description = ?, meta_description = ?, meta_keyword = ?, tag = ?, modified_by = ? WHERE product_id = ? AND language_id = ?";
$stmt = $mysqli->prepare($updateproduct_sql);
$stmt->bind_param('sssiiiss', $image, $ean, $model, $status, $price_sync, $modified_by, $date_modified, $product_id);
$stmt2 = $mysqli->prepare($updatedescription_sql);
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
while($row = $backup->fetch_array(MYSQLI_ASSOC))
{
//$name = removeslashes($row['name']);
$name = $row['name'];
//$description = removeslashes($row['description']);
$description = $row['description'];
$meta_description = $row['meta_description'];
$meta_keyword = $row['meta_keyword'];
$tag = $row['tag'];
$product_id = $row['product_id'];
$modified_by = $row['modified_by'];
$language_id = $row['language_id'];
if($row['language_id'] == 4)
{
$image = $row['image'];
$ean = $row['ean'];
$name = $row['name'];
$model = $row['model'];
$status = $row['status'];
$price_sync = $row['price_sync'];
$date_modified = $row['date_modified'];
if(!$stmt->execute())
return false;
}
if(!$stmt2->execute())
return false;
$i++;
if(($i % 500) === 0) $mysqli->commit();
}
$mysqli->commit();
$backup->close();
return true;
}
function removeslashes($string)
{
$string=implode("",explode("\\",$string));
return stripslashes(trim($string));
}
The error I get is
Fatal error: Call to a member function bind_param() on boolean in
Any suggestions, please? I do not see what am I doing wrong. Thank you all in advance.
The prepare() method can return false and you should check for that. As for why it returns false, perhaps the table name or column names (in SELECT, UPDATE or WHERE clause) are not correct?
Also, consider use of something like $query->error_list to examine errors that occurred parsing the SQL. (I'll occasionally echo the actual SQL statement strings and paste into phpMyAdmin to test, too, but there's definitely something failing there.)
I have to build up a sql statement and the params from a $place object that has a variable number of properties. When I use prepared sql statements by building the sql statement and params the long and bad practice way it works (returns all the rows from the database that it should):
<?
function buildSQLWhereClause($query, $conn, $place) {
if ($place['suburb']){
if($place['city'] && $place['province'] && $place['country']) {
$query .= "s.country = ? and
s.province = ? and
s.city = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $place['country'], $place['province'], $place['city'], $place['suburb']);
} else if ($place['province'] && $place['country']) {
$query .= "s.country = ? and
s.province = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $place['country'], $place['province'], $place['suburb']);
} else if ($place['city'] && $place['province']) {
$query .= "s.province = ? and
s.city = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $place['province'], $place['city'], $place['suburb']);
} else if ($place['city'] && $place['country']) {
$query .= "s.country = ? and
s.city = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $place['country'], $place['city'], $place['suburb']);
} else if ($place['city']) {
$query .= "s.city = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['city'], $place['suburb']);
} else if ($place['province']) {
$query .= "s.province = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['province'], $place['suburb']);
} else if ($place['country']) {
$query .= "s.country = ? and
s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['country'], $place['suburb']);
} else {
$query .= "s.suburb = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $place['suburb']);
}
//////////////////////////// NO SUBURB ///////////////////////////////////////////////////
} else if ($place['city']) {
if ($place['province'] && $place['country']) {
$query .= "s.country = ? and
s.province = ? and
s.city = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $place['country'], $place['province'], $place['city']);
} else if ($place['province']) {
$query .= "s.province = ? and
s.city = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['province'], $place['city']);
} else if ($place['country']) {
$query .= "s.country = ? and
s.city = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['country'], $place['city']);
} else {
$query .= "s.city = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $place['city']);
}
//////////////////////// NO SUBURB OR CITY ////////////////////////////////////////////////////////
} else if ($place['province']) {
if ($place['country']) {
$query .= "s.country = ? and
s.province = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $place['country'], $place['province']);
} else {
$query .= "s.province = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $place['province']);
}
//////////////////////////////// NO SUBURB, CITY, OR PROVINCE ///////////////////////////////
} else if ($place['country']) {
$query .= "s.country = ?";
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $place['country']);
}
return $stmt;
}
function queryDbForProducts($conn, $place)
{
$query = "SELECT p.*, s.*
FROM product p
INNER JOIN product_shop ps
ON ps.p_id = p.p_id
INNER JOIN shop s
ON s.s_id = ps.s_id
WHERE ";
$stmt = buildSQLWhereClause($query, $conn, $place);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] =& $row[$field->name];
}
When I use sql prepared statements by building up the sql statement and params the much better way, it doesn't work:
<?
function buildSQLWhereClause($place) {
$query = "SELECT p.*, s.* FROM product p INNER JOIN product_shop ps ON ps.p_id = p.p_id INNER JOIN shop s ON s.s_id = ps.s_id WHERE ";
$queryParams = [];
$queryParamTypes = "";
$i = 0;
$len = count($place);
foreach ($place as $key => $value) {
if ($i == $len - 1) {
$query .= "$key = ?";
$queryParams[] = $value;
$queryParamTypes .= "s";
} else {
$query .= "$key = ? AND ";
$queryParams[] = $value;
$queryParamTypes .= "s";
}
$i++;
}
return array(
"query" => $query,
"queryParams" => $queryParams,
"queryParamTypes" => $queryParamTypes
);
}
function queryDbForProducts($conn, $place)
{
$queryObject = buildSQLWhereClause($place);
$query = $queryObject['query'];
$queryParams = $queryObject['queryParams'];
$queryParamTypes = $queryObject['queryParamTypes'];
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param($queryParamTypes, $queryParams);
$stmt->execute();
$meta = $stmt->result_metadata();
Hovering over the $stmt in the debugger shows:
affected_rows:-1
insert_id:0
num_rows:0
param_count:4
field_count:13
errno:2031
error:"No data supplied for parameters in prepared statement"
error_list:array(1)
sqlstate:"HY000"
id:1
No data supplied? Hovering over the $queryParams parameter in the debugger shows:
0:"Grey Lynn"
1:"Auckland"
2:"Auckland"
3:"New Zealand"
So I did provide the query parameters to the $stmt->bind_param() function. Did I provide them in the wrong format?
Hovering over $QueryParamTypes shows:
"ssss"
Hovering over $query shows:
"SELECT p.*, s.* FROM product p INNER JOIN product_shop ps ON ps.p_id = p.p_id INNER JOIN shop s ON s.s_id = ps.s_id WHERE suburb = ? AND city = ? AND province = ? AND country = ?"
How come it works when done with the code at the top of the question and it doesn't work when done with the code without all the is statements?
bind_param does not take an array as an argument, it takes varargs. You will need to use call_user_func_array if you want to call it with a dynamic number of arguments.
i.e.
$params = array_unshift($queryParams, $queryParamTypes);
call_user_func_array(array($stmt, "bind_param"), $params);
The params passed to call_user_func_array, parameter 2, need to be referenced.
This is the working solution:
function makeValuesReferenced($arr){
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
$stmt = $conn->prepare($query);
//$stmt->bind_param($queryParamTypes, $queryParams);
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($queryParams));
$stmt->execute();
As per this answer
Not knowing about the reference thing mucked me around for a long time. Hope this helps some people.
I have this script:
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
$stmt->execute();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
And it is basically inserting around 157K (157 THOUSAND) rows of data. And the data is quite big as well! You can't check the file_get_contents URL out because the port is open only to localhost.
What is the quickest way to insert all this data? It has been running for almost 24 hours now and done 65K. I did try and use transactions but that didn't work well. It gave my 502 Bad Gateway and therefore I lost a lot of time on the script because it rolled back after adding 3 thousand rows (which was however quite quick!)
Also it is possible that the script may at some point fail and leave some of the varchar fields as null hence I have made it so that they end up as an empty string so that there aren't any mySql errors (I got those exceptions thrown when using transactions)
This is the code I used with the transaction stuff. I'm pretty new to prepared statements. I converted this code from standard queries to prepared today and then tried transactions.
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
try{
$con->autocommit(FALSE);
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
if(!$stmt->execute()){
throw new Exception("Cannot insert record. Reason :".$stmt->error);
}
}
$con->commit();
}catch (Exception $e) {
echo 'Transaction failed: ' . $e->getMessage();
$con->rollback();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
Thanks :)
$sql="
INSERT INTO
ue_game_alliance_rank_rights
(
rank
, `right`
)
VALUES
";
$insertQuery = array();
$insertData = array();
foreach ($rights_status['add'] AS $row ) {
$insertQuery[] = '(?,?)';
$insertData[] = $rank;
$insertData[] = $row['id'];
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $this->db->prepare($sql);
$stmt->execute($insertData);
}
}
That's an example of the basic technique, you would need to swap the functions for their equivalent mysqli_* functions. For each field having data inserted into it, you need:
$insertData[] = $row['id'];
$row needs to match whatever you've used in your foreach loop and ['id'] needs to be whatever the name of the field is that you're inserting into.
$insertQuery[] = '(?,?)';
You need as many placeholders as fields that you'll be inserting into.
Overall it creates a bulk insert, so you need to have the data to be inserted in an array. Given the amount of data that you're inserting, use transactions, you'll probably need to experiment to see how many rows you can bulk insert at a time before the server complains
I had a mysql query and I was converting it to mysqli(prepared statement) but I ran in to a problem which throws the below error,
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
Mysql code
$random_name_generated = vpb_generate_random_name().'.jpg'; //Generated name for uploaded files or images
if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], $final_uploads_location)) {
$check_empty_field = mysql_query("select * from `vpb_uploads` where `username` = '".mysql_real_escape_string(strip_tags($username))."' and `firstname` = '".mysql_real_escape_string("")."' and `lastname` = '".mysql_real_escape_string("")."'");
if (mysql_num_rows($check_empty_field) < 1) {
mysql_query("insert into `vpb_uploads` values('', '".mysql_real_escape_string($username)."', '', '', '".mysql_real_escape_string($random_name_generated)."', '', '', '', '', '".mysql_real_escape_string(date("d-m-Y"))."')");
$identity = "image_one";
} else {
$get_empty_field = mysql_fetch_array($check_empty_field);
$image_one = strip_tags($get_empty_field["image_one"]);
$image_two = strip_tags($get_empty_field["image_two"]);
$image_three = strip_tags($get_empty_field["image_three"]);
$image_four = strip_tags($get_empty_field["image_four"]);
$image_five = strip_tags($get_empty_field["image_five"]);
global $identity;
The below is what I tried even though it didn't work. I already knew it won't work but I wanted to try it myself before asking a question. And the error is coming from the $get_empty_field = $stmt->bind_result($stmt);
if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], $final_uploads_location)) {
$firstname = '""';
$lastname = '""';
$stmt = $mysqli->prepare("select * from `vpb_uploads` where `username` = ? and `firstname` = ? and `lastname` = ?");
$stmt->bind_param('sss', $username, $firstname, $lastname);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows < 1) {
$date = 'date("d-m-Y")';
$image_2 = "''";
$image_3 = "''";
$image_4 = "''";
$image_5 = "''";
$stmt = $mysqli->prepare("insert into `vpb_uploads` (`username`, `firstname`, `lastname`, `image_one`, `image_two`, `image_three`, `image_four`, `image_five`, `date`) values(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param('sssssssss', $username, $firstname, $lastname, $random_name_generated, $image_2, $image_3, $image_4, $image_5, $date);
$stmt->execute();
$stmt->close();
$identity = "image_one";
} else {
$get_empty_field = $stmt->bind_result($stmt);
$image_one = strip_tags($get_empty_field["image_one"]);
$image_two = strip_tags($get_empty_field["image_two"]);
$image_three = strip_tags($get_empty_field["image_three"]);
$image_four = strip_tags($get_empty_field["image_four"]);
$image_five = strip_tags($get_empty_field["image_five"]);
global $identity;
You need to change
$get_empty_field = $stmt->bind_result($stmt);
To
$get_empty_field = $stmt->bind_result($field1, $field2, $field3);
The number of $fieldx variables being equal to the number of fields that are selected. If you don't know how many there are, use this:
// Throw an exception if the result metadata cannot be retrieved
if (!$meta = $stmt->result_metadata())
{
throw new Exception($stmt->error);
}
// The data array
$data = array();
// The references array
$refs = array();
// Iterate over the fields and set a reference
while ($name = $meta->fetch_field())
{
$refs[] =& $data[$name->name];
}
// Free the metadata result
$meta->free_result();
// Throw an exception if the result cannot be bound
if (!call_user_func_array(array($stmt, 'bind_result'), $refs))
{
throw new Exception($stmt->error);
}
And then you access the result, after fetching, with $data['field'];