Post multidimensional array in Mysql - php

I want to post a multidimensional array into Mysql.
The code I have to know.
if (isset($_POST['husers[]'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, $_POST['husers[]']);
$query->execute();
}
The data I have:
array (size=4)
'text' => string 'bla' (length=3)
'another text' => &string '' (length=0)
'husers' =>
array (size=5)
0 => string '100486' (length=6)
1 => string '13474' (length=5)
2 => string '179339' (length=6)
3 => string '184729' (length=6)
4 => string '150593' (length=6)

The function serialize will do the trick for you.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, serialize($_POST['husers']));
$query->execute();
}
When you are pulling it out of the database you'll need to use the function unserialize to get it to a normal array.

You can use json_encode function of php. By this you can stora data as string. When retrieving it from database, by json_decodefunction yu can make it array again.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE
user_id = '" . $userId . "'");
$query->bindParam(1, json_eoncode($_POST['husers']));
$query->execute();
}

If you want to store the data as a simple comma-separate string:
if(isset($_POST['husers'])){ // changed $_POST key reference
$husers_csv=implode(',',$_POST['husers']);
$stmt=$db->prepare("UPDATE `users` SET highlighted_users=? WHERE user_id=?"); // removed (), added another placeholder
$stmt->bindParam(1,$husers_csv);
$stmt->bindParam(2,$user_id);
$status=$stmt->execute();
}

You can json_encode this data, then store it as a json string. When you pull the data back out simple json_decode() to get your array back.
if (isset($_POST['husers'])) {
$query = $db->prepare("UPDATE `users` SET highlighted_users = ( ? ) WHERE user_id = '" . $userId . "'");
$query->bindParam(1, json_encode($_POST['husers']));
$query->execute();
}

Related

MySQL - number of bound variables does not match number of tokens

Can't figure out why this code isn't working:
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([$SQL_values]);
And these are dumps of the two strings being inserted into those statements:
$SQL_update = UPDATE laptops SET asset_tag = :asset_tag WHERE id = :id
$SQL_values = 'asset_tag' => 5544, 'id' => 23
You missed : in your code:-
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([':asset_tag' => 5544, ':id' => 23]);
So actually what you have to do is:-
$SQL_values =[':asset_tag' => 5544, ':id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Or
$SQL_values =['asset_tag' => 5544, 'id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Note:- execute won't accept a string, it must be an array.

How to get a single value from a query result in php [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am trying to get single value from DB with single query. i mean that i already featched all values in one query from that i need to get only one column value.
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query( $connection,"select * from register where password='$log_in_password' AND username='$log_in_username'");
var_dump($query);
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
var_dump($table);
assume columns are
' userid useremail username password Name '
from php
var_dump($query) gives this..
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
var_dump($table) gives this
array (size=1)
0 =>
array (size=5)
'userid' => string '7' (length=1)
'useremail' => string 'demo#gmail.com' (length=16)
'username' => string 'demousername' (length=7)
'password' => string 'demopassword' (length=5)
'Name' => string 'demoname' (length=6)
so help me out with fetching only one column value's record (example insSelect * to select userid)
Your variable $table is an array, so if you want only the userid, you just have to use
$table[0]['userid']
If you want to query only the userid change you query like this :
$query = mysqli_query( $connection,"select userid from register where password='$log_in_password' AND username='$log_in_username'");
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
And the result of $table will be :
array (size=1)
0 =>
array (size=1)
'userid' => string '7' (length=1)
$table will also be an array, and to acces userid you have to use again
$table[0]['userid']
Try this
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query($connection, "select * from register where password='$log_in_password' AND username='$log_in_username'");
$table = null;
while ($row = mysqli_fetch_array($query)) {
$table = $row;
}
print_r($table);

MySQL returns null values for certain rows

I am having a problem with MySQL and PHP. I'm trying to create something that gets values from a database, encode it in JSON and then print it. I have that down, but there's something that is keeping from one certain row in the database from displaying. It always returns NULL except for the id value I set. Here's my code, am I doing something wrong?
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
If you want to take a look at it, it's hosted here. The funny thing is, this page uses the exact same code, but doesn't return null. Any ideas?
Edit:
Here's what is in $playerInfo (when I use geekygamer14)
array (size=3)
'id' => null
'name' => null
'server' => null
It seems that whatever rows that have verified set to 1 (integer), it gives NULL.
You're using variable $record in your loop, though this doesn't show in your generated array. Instead you're using a variable named $playerarray. I assume the code should be:
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Note: Consider using an alternative to mysql-functions, for example mysqli. Mysql-functions are deprecated.
Change this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
to this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Your variables name $playerarray['id'] is wrong this is write $record['id']. Your data is in $record because of loop so you should use $record instead of $playerarray.

PDO Update Set Where - parameter was not defined

I've spent hours looking at this and just don't see the mistake.
6 columns, 6 ?'s, 6 array elements.
The insert works fine the update is the problem!
Btw. is this a good way to deal with insert on duplicate update?
$userId = 13;
foreach($tableKey as $table=>$value){
foreach($value as $key=>$val){
$array_of_parameters[$key] = $val;
$fields[] = sprintf("%s=?", $key);
}
$field_list = join(', ', $fields);
try{
$update = "UPDATE `$table` SET $field_list WHERE id=$userId";
$stmt = $db->prepare($update);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);// here's where I get error!
if($stmt->rowCount() == 0){
$insert = "INSERT INTO `$table` (".implode(',', array_keys($value)).") VALUES (:".implode(',:', array_keys($value)).")";
$stmt = $db->prepare($insert);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);
}
}
}
Here's the debug and $array_of_parameters
array
'user' => string 'somebody' (length=3)
'first' => string 'some' (length=7)
'last' => string 'body' (length=4)
'zoneId' => string 'zone' (length=4)
'email' => string 'tst#me.net' (length=21)
'head' => string '1' (length=1)
SQL: [80] UPDATE `user` SET user=?, first=?, last=?, zoneId=?, email=?, head=? WHERE id=13 Params: 0
And of course the error
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Try calling array_values on $array_of_parameters before executing the statement.
For unnamed parameters, execute probably expects numeric (default) keys in your parameters array. Populate $array_of_parameters in order without keys, then try it.

PHP array to mysql BD... missing array fields

Need your help.
I need to update the array data in the mysql table. my problem is that there are some array values which dont have "photo" coloum (check 4th field in the array) because of that my query is failing with error "Column count doesn't match value count at row 1"
below is what im trying.
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
$sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());
Array Data
array
0 =>
array
'dob' => string '01121978'
'name' => string 'Ram Avtar'
'role' => string 'Inspector'
'email' => string 'ramavtar#gmail.com'
'photo' => string ' '
1 =>
array
'dob' => string '15021978'
'name' => string 'Suresh Babu'
'role' => string 'Constable'
'email' => string 'ssbh1#mail.yahoo.com'
'photo' => string ' '
2 =>
array
'dob' => string '11111965'
'name' => string 'Dean'
'role' => string 'Inspector'
'email' => string 'ddepth#live.in'
'photo' => string ' '
3 =>
array
'dob' => string '10061979'
'name' => string 'Rohit Shette'
'role' => string 'Sergeant'
'email' => string ' '
'photo' => string ' '
4 =>
array
'dob' => string '15081979'
'name' => string 'Ian'
'role' => string 'warden'
'email' => string ' '
table structure
CREATE TABLE user(
id INT(5) NOT NULL AUTO_INCREMENT,
dob TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT DEFAULT NULL,
email TEXT DEFAULT NULL,
photo TEXT DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
The actual problem is that you missed a comma.
Change:
echo $sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
To:
$sql[] = "('{$row['dob']}', '{$row['name']}', '{$row['role']}',
'{$row['email']}', '{$row['photo']}')"; // ^^^ Here is the missing comma
The missing values will not cause a problem, they will just cause an empty string to be inserted, because the string is quoted. However, you may wish to test to make sure the key exists in the array array before you try to use it, to avoid any nasty E_NOTICEs.
Also, make sure you properly escape your data before you use it in a query - you don't want a visit from Bobby Tables...
First - if that's your real code I think you're missing a comma after $row['role']. Also - why not check if array key exists?
Try something like (not tested, just to give you an idea)
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
echo $sql[] = '('
. (array_key_exists('dob', $row) ? $row['dob'] : 'null') . ', "'
. (array_key_exists('name', $row) ? $row['name'] : 'null') . '", "'
. (array_key_exists('role', $row) ? $row['role'] : 'null') . '", "'
. (array_key_exists('email', $row) ? $row['email'] : 'null') . '", "'
. (array_key_exists('photo', $row) ? $row['photo'] : 'null') . '" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());

Categories