type "lvarchar" sql in array php - php

I have a problem when displaying data from an odbc database, I have a column of type "LVARCHAR" that allows me to insert texts with more than 1,000 characters. In my code I put this sql in an array, but it is not displaying, the array only displays the description with (255 characters) if it is more it does not display, what could I do?
I put a var_dump to display my array that comes from the database, as you can see the "description" is null, and I have a small text in it
array(18) {
["id"]=> string(1) "1"
["usuario"]=> string(30) "adm "
["data_inclusao"]=> string(10) "2023-02-03"
["descricao"]=> NULL
["figura1"]=> NULL
}
$pdo = Banco::conectar();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM esp_cad_etiq
WHERE id = ?
AND cod_matriz = $cod_matriz
";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
Banco::desconectar();

Related

Data type differences between PHP sqlsrv driver and PDO driver

Here I am using sqlsrv:
$conn = sqlsrv_connect("192.168.1.102,1433", array("Database"=>"RF_User", "UID"=>"rfo-gcp", "PWD" => ""));
$tsql = "SELECT birthdate FROM tbl_rfaccount WHERE id = ?";
$stmt = sqlsrv_query($conn, $tsql, array("test"));
$result = sqlsrv_fetch_array($stmt);
var_dump($result);
Result: array(2) { [0]=> object(DateTime)#1 (3) { ["date"]=> string(26) "2020-04-19 20:40:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } ["birthdate"]=> object(DateTime)#1 (3) { ["date"]=> string(26) "2020-04-19 20:40:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } }
Here I am using PDO:
$conn = new PDO("sqlsrv:Server=192.168.1.102,1433; Database=RF_User;", "rfo-gcp", "");
$tsql = "SELECT birthdate FROM tbl_rfaccount WHERE id = cast(? as varchar(13))";
$stmt = $conn->prepare($tsql);
$stmt->execute(array("test"));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($result);
Result: array(1) { ["birthdate"]=> string(19) "2020-04-19 20:40:00" }
If you notice, I had to use cast(? as varchar(13)) on the PDO code. Without it would not return any row. On the sqlsrv I didn't have to use the CAST() function. Why is this? Also, the id column on the database is a BINARY(13), so why do I have to cast the id to varchar and not to binary (with binary cast it also doesn't find the row)?
Why date and time values are returned differently?
In fact, this is only a setting.
When you use PDO_SQLSRV (as is mentioned in the documentation), date and time types (smalldatetime, datetime, date, time, datetime2, and datetimeoffset) are by default returned as strings. Neither the PDO::ATTR_STRINGIFY_FETCHES nor the PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE attribute has any effect. In order to retrieve date and time types as PHP DateTime objects, set the connection or statement attribute PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE to true (it is false by default).
When you use SQLSRV driver (again from the documentation), smalldatetime, datetime, date, time, datetime2, and datetimeoffset types will be returned as PHP DateTime objects. This behaviour can be changed by setting the 'ReturnDatesAsStrings' option in the connection string or at the statement level.
$conn = sqlsrv_connect(
"192.168.1.102,1433",
array(
"ReturnDatesAsStrings"=>true,
"Database"=>"RF_User",
"UID"=>"rfo-gcp",
"PWD" => ""
)
);
Note that some of the features depend on the version of PHP Driver for SQL Server.
How to cast parameters values?
Using CAST() and CONVERT() functions in the statement and binding parameter value with string value should work. Of course, you can specify the parameter data type, when you bind a parameter.
For PDO_SQLSRV you should extended syntax for PDOStatement::bindParam().
For SQLSRV you may use the extended $params syntax to specify the SQL Server data type, when you make a call to sqlsrv_query()\sqlsrv_execute().
I'm able to reproduce this issue (PHP 7.1.12, PHP Driver for SQL Server 4.3.0+9904, SQL Server 2012) and the solution is to use:
$params = array($id, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_BINARY); // SQLSRV
$stmt->bindParam(1, $id, PDO::PARAM_LOB, null, PDO::SQLSRV_ENCODING_BINARY); // PDO_SQLSRV
Table:
CREATE TABLE tbl_rfaccount (id binary(13), birthdate datetime)
INSERT INTO tbl_rfaccount (id, birthdate) VALUES (CONVERT(binary(13), 'Test'), GETDATE())
PHP:
<?php
...
//
$id = "Test";
// SQLSRV
$tsql = "SELECT birthdate FROM tbl_rfaccount WHERE id = ?";
$params = array($id, SQLSRV_PARAM_IN, null, SQLSRV_SQLTYPE_BINARY);
$stmt = sqlsrv_query($conn, $tsql, $params);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
$result = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
var_dump($result);
// PDO_SQLSRV
$tsql = "SELECT birthdate FROM tbl_rfaccount WHERE id = ?";
$stmt = $conn->prepare($tsql);
$stmt->bindParam(1, $id, PDO::PARAM_LOB, null, PDO::SQLSRV_ENCODING_BINARY);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($result);
...
?>

Querys wont work on MSSQL Server 2016 with PDO connection over sqlserv [duplicate]

I have a problem when I get number of rows in SQL Server 2008 because my code works fine using MySQL but not in SQL Server.
$sql = "SELECT TOP 1 U.Id , U.Name, U.Profile, P.Name NameProfile
FROM sa_users U
INNER JOIN sa_profiles P ON P.Id = U.Profile
WHERE User = :user AND Pass = :pass";
$result = $this->dbConnect->prepare($sql) or die ($sql);
$result->bindParam(':user',$this->data['username'],PDO::PARAM_STR);
$result->bindParam(':pass',$this->data['password'],PDO::PARAM_STR);
if (!$result->execute()) {
return false;
}
$numrows = $result->rowCount();
$jsonLogin = array();
var_dump($numrows);
if($numrows > 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$jsonLogin = array(
'name' => $row['Name'],
'id' => $row['Id'],
'profile' => $row['Profile'],
'n_profile' => $row['NameProfile']
);
}
$jsonLogin['area'] = 'another';
return $jsonLogin;
} else {
return false;
}
var_dump($result->fetch()) in MySQL and SQL Server
array(8) {
["Id"]=>
string(1) "1"
[0]=>
string(1) "1"
["Nombre"]=>
string(13) "Administrador"
[1]=>
string(13) "Administrador"
["Perfil"]=>
string(1) "1"
[2]=>
string(1) "1"
["NomPerfil"]=>
string(13) "Administrador"
[3]=>
string(13) "Administrador"
}
var_dump($numrows) in SQL Server
int(-1)
var_dump($numrows) in MySQL
int(1)
Regards.
I know it's a bit of an old thread, but I had the similar question this morning and there's actually a way for the rowcount() function to work with SQL server.
I'm using a connection string like this (to connect to a SQL server database):
$connection = new PDO("sqlsrv:Server=" . $this->sourceServer . ";Database=" . $this->sourceDB, $this->sourceUser, $this->sourcePW);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
And when I want to use a query for which I need to know the number of row to return (with SQL server), I use PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL as second parameter of PDO prepare function just like this:
$rs = $connection->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
Here's the example from Microsoft website: https://msdn.microsoft.com/en-us/library/ff628154(v=sql.105).aspx
Well, it's never too late to share a good solution,
Jonathan Parent-Lévesque from Montreal
Just add $result = $stmt->fetchAll(); after $stmt->execute();
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$numrows = $stmt->rowCount();
Just quoting the manual:
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not guaranteed
for all databases and should not be relied on for portable
applications.
You don't actually need this function. As well as most of the other code
$result = $this->dbConnect->prepare($sql);
$result->bindParam(':user',$this->data['username']);
$result->bindParam(':pass',$this->data['password']);
$result->execute();
$jsonLogin = $result->fetch(PDO::FETCH_ASSOC));
if ($jsonLogin) {
$jsonLogin['area'] = 'another';
return json_encode($jsonLogin);
}
is all the code you need.

Multiple PHP mysqli prepared statements (INSERT UPDATE SELECT) weird behavior [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
I have a problem using following PHP function:
function saveCommentOnDB($arg_textComment, $arg_score, $arg_userEmail)
{
$result_tmp = null;
$this->conn->autocommit(false);
echo "saving\n";
echo "text comment: \n";
var_dump($arg_textComment); // OKAY
echo "comment score: \n";
var_dump($arg_score); // OKAY
echo "user mail: \n";
var_dump($arg_userEmail); // OKAY
try {
//[tag1] $query_1 = "INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = 'asd#asd.asd') ,'asd#asd.asd', 'This is an example comment.', 5, 0);";
$query_1 = "INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = ?) ,?,?, ?, 0);";
$query_2 = "UPDATE utente SET commentID=(SELECT c.commentID FROM commenti c WHERE c.userEmail = ?) WHERE userEmail = ?;";
$query_3 = "SELECT commentID, textComment FROM commenti WHERE userEmail = ?;";
$stmt1 = $this->conn->prepare($query_1);
$stmt2 = $this->conn->prepare($query_2);
$stmt3 = $this->conn->prepare($query_3);
$stmt1->bind_param("sssd", $arg_userEmail, $arg_userEmail, $arg_textComment, $arg_score);
$stmt2->bind_param("ss", $arg_userEmail, $arg_userEmail);
$stmt3->bind_param("s", $arg_userEmail);
$stmt1->execute();
$stmt2->execute();
$stmt3->execute();
$stmt3->bind_result($col1, $col2);
$stmt3->fetch();
echo "result:\n";
var_dump($col1); // OKAY
var_dump($col2); // OKAY
$result_tmp = array(
'commentID' => $col1,
'textComment' => $col2
);
$this->conn->commit();
} catch (Exception $e) {
$this->conn->rollback();
}
return $result_tmp;
}
Please, ignore the echo and var_dump, I put them only for debugging.
The problem is that in this function these three prepared statement seems to work not correctly. In particular the statement $stmt1: the result of $stmt3 is correct (as if $stmt1 and $stmt2 are executed correctly), but I don't see anything on my Database. In other words: the statements works correctly 'temporarily' during the execution, but in MyPHP Admin there's nothing on the table commenti.
For example, we assume having this on the DB:
Now I launch the function with following parameters:
$arg_textComment = 'This is an example comment'
$arg_score = '5'
$arg_userEmail = 'asd#asd.asd'
and we have on my browser console:
ie: the commentID (28) is right and the comment text (commentcomment) was "saved", then I recheck the DB but I have still this:
and var_dump($stmt1) after the execution is:
stmt1:
object(mysqli_stmt)#4 (10) {
["affected_rows"]=>
int(1)
["insert_id"]=>
int(41)
["num_rows"]=>
int(0)
["param_count"]=>
int(4)
["field_count"]=>
int(0)
["errno"]=>
int(0)
["error"]=>
string(0) ""
["error_list"]=>
array(0) {
}
["sqlstate"]=>
string(5) "00000"
["id"]=>
int(4)
}
The var_dump seems to be ok, but DB nope.
So I try to execute the query 'manually' by this (it will be executed only the code into the green lined box):
and I have what I expected:
sql> INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = 'asd#asd.asd') ,'asd#asd.asd', 'commentcomment', '5', 0) [2017-01-21 17:38:28] 1 row affected in 11ms
Keep in mind score value is store on DB as float.
The SQL query of the $stmt1 is the same I inserted manually (INSERT INTO... via PHPStorm).
Why the first doesn't works and instead the second yes?
Hope this screencast may help:
https://youtu.be/UsYK93jYVqA
Problem solved, change from this:
$stmt1->execute();
$stmt2->execute();
$stmt3->execute();
to this:
$stmt1->execute();
$this->conn->commit();
$stmt2->execute();
$this->conn->commit();
$stmt3->execute();
$this->conn->commit();
Have no idea of why... 😐 but it works after many tests.

PHP not inserting autoincrement field in a MySQL temporary table

I have created a temporary table with the following PHP script
$query = "CREATE TEMPORARY TABLE people(id int(11) not null auto_increment, first_name varchar(25), second_name varchar(25), primary key(id))";
$q=$pdo->prepare($query);
$q->execute();
I then tried to insert data to this table with the following script
$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2=$pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname,PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname,PDO::PARAM_STR);
$q2->execute;
The data I am trying to insert comes from another table. At first this seemed as a problem caused by an elementary error but I cannot figure out where the problem is because when I run this script (see below), I see that all fields were created
$query3 = "DESCRIBE people";
$q3 = $con->prepare($query3);
$q3->execute();
$row = $q3->fetchAll(PDO::FETCH_COLUMN);
print_r($row);
$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2=$pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname,PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname,PDO::PARAM_STR);
$q2->execute;
The () for the execute() method are missing.
Additionaly:
If you are trying to fill the table from another table, without other steps in between, you could do this directly via mysql:
$query2 = "INSERT INTO people(first_name, second_name)
select firstname, secondname from otherTABLE where something = 'xy'";
$pdo->exec($query2);
Doing it directly in the database would reduce the chance for errors in php trying to do the same.
The rest of your script is correct, I tested it locally:
$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '', array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
$query = "CREATE TEMPORARY TABLE people(id int(11) not null auto_increment, first_name varchar(25), second_name varchar(25), primary key(id))";
$q = $pdo->prepare($query);
$q->execute();
$firstname = 'test';
$secondname = 'what';
$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2 = $pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname, PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname, PDO::PARAM_STR);
$q2->execute();
$pdo->exec("INSERT INTO people(first_name, second_name) SELECT 'prename', 'surname'");
$result = $pdo->query('SELECT * FROM people');
echo '<pre>';
var_dump($result->fetchAll());
exit;
displays:
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["first_name"]=>
string(4) "test"
["second_name"]=>
string(4) "what"
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["first_name"]=>
string(7) "prename"
["second_name"]=>
string(7) "surname"
}
}

How can I get all the values of a column using PHP [duplicate]

This question already has answers here:
How get all values in a column using PHP?
(7 answers)
Closed 7 years ago.
After this question, what is the best way to get all the values of a single column in a MySQL database?
For instance, all values of:
SELECT Name FROM Customers
Looking for a non-deprecated answer.
Here is a simple way to do this using PDO
$stmt = $pdo->prepare("SELECT Column FROM foo LIMIT 5");
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_GROUP);
var_dump(array_keys($array));
array(5) {
[0]=>
int(7960)
[1]=>
int(7972)
[2]=>
int(8028)
[3]=>
int(8082)
[4]=>
int(8233)
}
$link = mysqli_connect($host, $user, $password) or die('DB Server Connection error'.mysqli_error());
mysqli_select_db($link, $database) or die('DB Selection error'.mysqli_error());
$sql = 'SELECT name FROM Customers';
$query = mysqli_query($link, $sql);
if (0 < mysqli_num_rows($query)) {
while ($data = mysqli_fetch_assoc($query)) {
$resultArray[] = $data['name'];
}
}

Categories