PHP, invalid SQL request - php

$query = 'SELECT name FROM users';
$stmt = $db->prepare($query);
$stmt->execute();
works well. Now I change my code just a bit
$query = 'SELECT RIGHT(name, 2) FROM users';
$stmt = $db->prepare($query); // returns false
$stmt->execute(); // throws an error
Does not work. var_dump($db->errorInfo()) outputs this
array (size=3)
0 => string 'HY000' (length=5)
1 => int 17
2 => string 'near "(": syntax error' (length=22)
What's the problem? name is a varchar string and it is longer than 2 symbols and never null.

Related

Storing Arrays in DB gives PHP Notice Undefined Offset 1

Getting an array from Android Client. Storing it in the DB gives a Notice: Undefined offset: 1 in C:\filepath\ on line 67
I am trying to achieve this in my DB:
User_Id | Book_Id
---------|---------
3 | 120
---------|---------
1 | 17
---------|---------
php file that collects the post from android client:
if(isset($_POST['watch'])){
$jsonwatch = $_POST['watch'];
$array = json_decode($jsonwatch, true);
$response["error"] =! ($db_watch->storeClass($array['attendees'], $array['lesson_iDs']));
}
php file that is called in the notice:
public function storeClass($attendees, $lesson_iDs) {
$stmt = $this->conn->prepare("INSERT INTO watch (date, user_id, lesson_id) VALUES(NOW(), ?, ?)");
$stmt->bind_param("ii", $attendees, $lesson_id);
foreach ($attendees as $index => $attendee) {
$lesson_id = $lesson_iDs[$index]; // Line 67
$result = $stmt->execute();
if(!$result){
echo '\n';
printf("Error for attendee %d in lesson %d : %s.\n", $attendee, $lesson_id, $stmt->error);
echo '\n';
echo '\n';
}
}
$stmt->close();
// result
return $result;
}
UPDATE!
var_dump($array):
C:\wamp64\www\ghanaweb\AddClass.php:19:
array (size=4)
'attendees' =>
array (size=2)
0 => string '5a6611e89e9e26.27646060' (length=23)
1 => string '5a4cfae69fd7b6.01373362' (length=23)
'id' => int 0
'lesson_iDs' =>
array (size=1)
0 => int 4
'lesson_id' => int 0
{"error":false}
Your problem is that you use the $ index as the ID in your case and it's only the number of the masive and nothing more
Try to use
$lesson_id = $lesson_iDs[$attendee['lesson_id']];
$lesson_iDs array has only one element and in the for loop you are trying to access a second element which is not existing

Post multidimensional array in Mysql

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();
}

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);

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.

PDO::FETCH_CLASSTYPE - unexpected result

I'am at loss here. Not sure why I'm getting "stdClass". Shouldn't I be getting name from 1st column?
$sql = "SELECT cn, iso2, iso3, fid, sort FROM ct";
$stmt = $dbh->query($sql);
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );
var_dump($result);
//expected - first: cn.col holds country names
object(Brazil)[3]
public 'iso2' => string 'BR' (length=2)
public 'iso3' => string 'BRA' (length=3)
public 'fid' => string '1' (length=1)
public 'sort' => string '0' (length=1)
//received
object(stdClass)[3]
public 'iso2' => string 'BR' (length=2)
public 'iso3' => string 'BRA' (length=3)
public 'fid' => string '1' (length=1)
public 'sort' => string '0' (length=1)var_dump
The issue is most likely that the class is not defined (or in scope). I did some testing using local data.
$conn = new PDO("mysql:host=localhost;dbname=test", 'user', 'pass');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$stmt = $conn->prepare("SELECT name,email FROM `test_table`");
$stmt->execute();
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );
print_r($result) // returns stdClass Object ( [email] => 'test#test.com' )
By adding this above the PDO code
Class levi{
}
I was able to get it to return:
levi Object ( [email] => 'test#test.com')

Categories