I cannot seem to figure out what is wrong and why i keep getting these errors
Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\test-site\php\include\dataFunc.inc on line 37
Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in C:\dataFunc.inc on line 38
I have checked and read the php doc and $smt is an objected returned by mysqli_prepare, but here is my function:
function storeData($form_data, $table_name, $cxn){
if(!is_array($form_data)){
return false;
exit();
}
$types = str_repeat("s", count($form_data));
$params = array();
$params[] = &$types;
$keys = array_keys($form_data);
$values = array_values($form_data);
for ($i = 0; $i < count($values); $i++) {
$params[] = &$values[$i];
}
$sql = "INSERT INTO $table_name (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")
ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
$stmt = mysqli_prepare($cxn, $sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
return mysqli_stmt_execute($stmt);
}
Edited: Here is what my sql query is returning:
$sql"INSERT INTO interest
(Baseball,Basketball,Camping,Canoeing,Cycling,Football,Gaming,Golf,Hiking,Parks,Photography,Runway,Skydiving,Soccer,Username) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE Baseball = VALUES(Baseball),Basketball = VALUES(Basketball),Camping = VALUES(Camping),Canoeing = VALUES(Canoeing),Cycling = VALUES(Cycling),Football = VALUES(Football),Gaming = VALUES(Gaming),Golf = VALUES(Golf),Hiking = VALUES(Hiking),Parks = VALUES(Parks),Photography = VALUES(Photography),Runway = VALUES(Runway),Skydiving = VALUES(Skydiving),Soccer = VALUES(Soccer),Username = VALUES(Username)"
$stmt?
$table_name"interest"
$types"sssssssssssssss"
$updates"Baseball = VALUES(Baseball),Basketball = VALUES(Basketball),Camping = VALUES(Camping),Canoeing = VALUES(Canoeing),Cycling = VALUES(Cycling),Football = VALUES(Football),Gaming = VALUES(Gaming),Golf = VALUES(Golf),Hiking = VALUES(Hiking),Parks = VALUES(Parks),Photography = VALUES(Photography),Runway = VALUES(Runway),Skydiving = VALUES(Skydiving),Soccer = VALUES(Soccer),Username = VALUES(Username)"
Related
Trying to create a function that would be used to update any row of any table, but I'm getting trouble getting into it.
Data sent in array where the array index is the field name in table and the value is the new value for that index.
For examplpe:
$args["name"] = "NewName";
$args["city"] = "NewCity";
$args["id"] = 4; // row ID to update
What I got:
function create_update_query($table, $keys){
$keys = array_map('escape_mysql_identifier', $keys);
$table = escape_mysql_identifier($table);
$updates = "";
$count = 0;
foreach($keys as $index => $value){
if($index != "id"){
$count++;
if($count == count($keys)-1){
$updates = $updates . "$index = ?";
}else{
$updates = $updates . "$index = ?,";
}
}
}
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
}
After that, I have the function to really do the query:
function crud_update($conn, $table, $data){
$sql = create_update_query($table, array_keys($data));
if(prepared_query($conn, $sql, array_values($data))){
$errors [] = "OK";
}else{
$errors [] = "Something weird happened...";
}
}
The function that makes the prepared statement itself:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
if($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo "<br/>".$error;
}
}
When trying to submit the data with the following criteria:
$args['name'] = "Novo Nome";
$args['field'] = "New Field";
$args['numaro'] = 10101010;
$args['id'] = 4;
//create_update_query("teste_table", $args);
crud_update($link, "teste_table", $args);
Have an error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 = ?,2 = ?,3 = ? WHERE id = ? LIMIT 1' at line 1
But if I echo the query created by create_update_query it seems ok:
UPDATE `teste_table` SET name = ?,field = ?,numaro = ? WHERE id = ? LIMIT 1
Any help would be appreciated.
Thanks.
The problem is that as you pass the keys to create_update_query() as
create_update_query($table, array_keys($data));
Using array_keys() will just take the key names, so the $keys parameter is just a list of the field names as something like ...
Array(
0=> 'name',
1 =>'field',
2 =>'numaro'
)
You then extract the data using
foreach($keys as $index => $value){
and build your SQL with
$updates = $updates . "$index = ?";
so at this point, the indexes are the numeric value, so change these lines to...
$updates = $updates . "$value = ?";
which is the name of the field.
With the various other changes, I would suggest the code should be...
foreach($keys as $value){
if($value != "id"){
$updates = $updates . "$index = ?,";
}
}
$updates = rtrim($updates, ",");
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
I am attempting to bind params to a sql statement using call_user_func_array as describe on Dynamically Bind Params in Prepared Statements with MySQLi; however, my mysqli_prepare keeps returning false.
Here is my data function that is called to store data:
function storeData($form_data, $table_name, $cxn){
if(!is_array($form_data)){
return false;
exit();
}
$types = str_repeat("s", count($form_data));
$params = array();
$params[] = &$types;
$keys = array_keys($form_data);
$values = array_values($form_data);
for ($i = 0; $i < count($values); $i++) {
$params[] = &$values[$i];
}
$sql = "INSERT INTO $table_name (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")
ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
if($stmt = mysqli_prepare($cxn, $sql)){
call_user_func_array(array($stmt, 'bind_param'), $params);
return mysqli_stmt_execute($stmt);
}
Here is my $sql string at time of prepare:
$sql"INSERT INTO interest (Baseball,Basketball,Camping,Canoeing,Cycling,Football,Gaming,Golf,Hiking,Parks,Photography,Runway,Skydiving,Soccer,Username) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE Baseball = VALUES(Baseball),Basketball = VALUES(Basketball),Camping = VALUES(Camping),Canoeing = VALUES(Canoeing),Cycling = VALUES(Cycling),Football = VALUES(Football),Gaming = VALUES(Gaming),Golf = VALUES(Golf),Hiking = VALUES(Hiking),Parks = VALUES(Parks),Photography = VALUES(Photography),Runway = VALUES(Runway),Skydiving = VALUES(Skydiving),Soccer = VALUES(Soccer),Username = VALUES(Username)"
Here is my $params and $key outputs:
$keysarray[15]
$keys[0]"Baseball"
$keys[1]"Basketball"
$keys[2]"Camping"
$keys[3]"Canoeing"
$keys[4]"Cycling"
$keys[5]"Football"
$keys[6]"Gaming"
$keys[7]"Golf"
$keys[8]"Hiking"
$keys[9]"Parks"
$keys[10]"Photography"
$keys[11]"Runway"
$keys[12]"Skydiving"
$keys[13]"Soccer"
$keys[14]"Username"
$paramsarray[16]
$params[0]"sssssssssssssss"
$params[1]"0"
$params[2]"0"
$params[3]"0"
$params[4]"0"
$params[5]"0"
$params[6]"0"
$params[7]"0"
$params[8]"0"
$params[9]"0"
$params[10]"0"
$params[11]"0"
$params[12]"0"
$params[13]"0"
$params[14]"0"
$params[15]"test0613"
$valuesarray[15]
$values[0]"0"
$values[1]"0"
$values[2]"0"
$values[3]"0"
$values[4]"0"
$values[5]"0"
$values[6]"0"
$values[7]"0"
$values[8]"0"
$values[9]"0"
$values[10]"0"
$values[11]"0"
$values[12]"0"
$values[13]"0"
$values[14]"test0613"
There error existed in a column i was attempting to map which did not exist. The error procedure was found here, which allowed me to produce fatal errors that noted a column did not exist in the table I was referencing.
I have this script trying to put array into mysqli_stmt_bind_param, I googled around and found this solution, however, the code doesn't seems to be working properly. I received no results from database and a warning.
Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object
Here is my code:-
$sql_param = array();
$params = array();
$query = "SELECT campname,url,views,leads,subs,country,affid FROM camp WHERE";
if (isset($_POST['fromdatetime']) && isset($_POST['todatetime'])) {
$datefrom = $_POST['fromdatetime'].":00";
$dateto = $_POST['todatetime'].":59";
$sql_param[] = $datefrom;
$sql_param[] = $dateto;
$bindparam = "ss";
$query .= "datevisit between (?) AND (?)";
}
if (isset($_POST['affidcode'])) {
$affidcode = $_POST['affidcode'];
$sql_param[] = $affidcode;
$bindparam .= "s";
$query .= " AND affid = (?)";
}
$sql_param_count = count($sql_param);
$params[] = &$bindparam;
for($i = 0; $i < $sql_param_count; $i++) {
$params[] = &$sql_param[$i];
}
/* create a prepared statement */
$stmt = mysqli_prepare($mysqli, $query);
call_user_func_array(array($stmt, 'mysqli_stmt_bind_param'), $params);
/* execute query */
$status = mysqli_stmt_execute($stmt);
Ensure that $stmt is valid mysqli_stmt object (not false) after this block:
/* create a prepared statement */
$stmt = mysqli_prepare($mysqli, $query);
Then try this:
array_unshift($params, $stmt);
call_user_func_array('mysqli_stmt_bind_param', $params);
Hi I have some problems with merging my array and bind my params.
Error Message = Warning: mysqli_stmt::bind_param(): Number of elements
in type definition string doesn't match number of bind variables
in.......
$headline = $_GET['hl'];
$county = $_GET['ca'];
$categories = $_GET['co'];
$query = 'SELECT COUNT(id) FROM main_table';
$queryCond = array();
$stringtype = array();
$variable = array();
if (!empty($headline)) {
$queryCond[] = "headline LIKE CONCAT ('%', ? , '%')";
array_push($stringtype, 's');
array_push($variable, $headline);
}
if (!empty($county)) {
$queryCond[] = "county_id = ?";
array_push($stringtype, 'i');
array_push($variable, $county);
}
if (!empty($categories)) {
$queryCond[] = "categories_id = ?";
array_push($stringtype, 'i');
array_push($variable, $categories);
}
if (count($queryCond)) {
$query .= ' WHERE ' . implode(' AND ', $queryCond);
}
//var_dump($query);
$stmt = $mysqli->prepare($query);
$variable = array_merge($stringtype, $variable);
print_r($variable);
//var_dump($refs);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
call_user_func_array(array($stmt, 'bind_param'), $refs);
You need change this:
$variable = array_merge($stringtype, $variable);
$refs = array();
foreach($variable as $key => $value)
$refs[$key] = &$variable[$key];
to this:
$variable = array_combine($stringtype, $variable);
Because array_combine() create an array by using one array for keys and another for its values.
Read more at:
http://php.net/manual/en/function.array-combine.php
It's a bit late answer, but I had issue with dynamically adding values.
If you have php v +5.6, you can omit this part
$variable = array_merge($stringtype, $variable);
// and $refs
call_user_func_array(array($stmt, 'bind_param'), $refs);
and using ...token introduced in +5.6v.
Here is a fully work example for my case:
// establish mysqli connection
$conn = new mysqli(.....);
$tableName = 'users';
// Types to bind
$type = 'isss';
$fields = ['id','name', 'email', 'created'];
$values = [1, 'name', 'email#test.com', '2018-1-12'];
$sql = "INSERT INTO " . $tableName . " (" . join(',', $fields) . ") VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
// Using ...token introduced in php v.5.6 instead of call_user_func_array
// This way references can be omitted, like for each value in array
$stmt->bind_param($type, ...$values);
$stmt->execute();
$stmt->close();
I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.