How to prepare a PHP postgreSQL request with 'LIKE' keyword - php

i'm using Symfony4 and a postgreSQL database. i'm working on a search system. I would like to check if something match with the string i'm sending with ajax in my database. But the SQL query always returns false. How should i do to make this code works ? Thanks for help :)
public function search(Request $request) : Response {
if($ajaxRequest = $request->getContent())
{
$requestContent = json_decode($ajaxRequest, true);
$content = $requestContent["content"];
$connexionParams = "host=localhost port=5432 dbname=mydb user=myuser password=mypassword";
$db = pg_connect($connexionParams);
$sql = pg_prepare($db, 'search_query', "SELECT nom, lon, lat, id FROM site WHERE nom LIKE $1 OR id LIKE $2");
$result = pg_execute($db, 'search_query', array($content, $content));
var_dump($content, pg_fetch_row($result), $result);
$results = array();
while($row = pg_fetch_row($result)) {
$results[] = $row;
}
if(($results)) {
return new JsonResponse([
'result' => true,
'results' => json_encode($results),
]);
} else {
return new JsonResponse([
'result' => false,
]);
}
}
}

false means failure, not empty zero hits as stated here. Most likely there is an error in your SQL Syntax or connection data. Maybe pg_last_error helps to find the mistake:
if ($result === false) {
echo pg_last_error($db);
}

Related

Getting synxtax error when trying to echo sql results as json datatype

I'm trying to output the sql results of the statement in json datatype, but an error was prompt SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data, I have checked my sql statement and try to executed in sql editor and it works, but im not sure why it doesnt work when im trying to echo it in the browser.
So i have a big switch statement block, and this is a small part of it, so basically when i type http://localhost/w11/local-html/part_1/api/schedule it should output json datatype by taking in the arguments from the url like api/schedule and api is arg_1 and schedule is arg_2.
case 'api':
{
header("Content-Type: application/json");
switch ($param2) {
case 'schedule':
{
switch ($param3) {
case '':
{
try {
$sqlQuery = "SELECT room, type, title, day, time FROM sessions INNER JOIN slots ON sessions.slotsID = slots.id";
$response = new JSONRecordSet();
$response = $response->getJSONRecordSet($sqlQuery, "");
echo $response;
} catch (PDOException $e) {
echo "Connection Failed:" . $e->getMessage();
}
break;
}
default:
{
//do something
break;
}
}
break;
}
This is the function for getJSONRecordSet
class JSONRecordSet extends RecordSet {
function getJSONRecordSet($sql, $params = null) {
$queryResult = $this->getRecordSet($sql, $params);
$recordSet = $queryResult->fetchAll(PDO::FETCH_ASSOC);
$nRecords = count($recordSet);
if ($nRecords == 0) {
$status = 200;
$message = array("text" => "No records found");
$result = '[]';
}
else {
$status = 200;
$message = array("text" => "");
$result = $recordSet;
}
return json_encode(
array(
'status' => $status,
'message' => $message,
'data' => array(
"RowCount"=>$nRecords,
"Result"=>$result
)
),
JSON_PRETTY_PRINT
);
}
}
And the parent class
abstract class RecordSet {
protected $conn;
protected $queryResult;
function __construct() {
$this->conn = pdoDB::getConnection();
}
function getRecordSet($sql, $params = null) {
if (is_array($params)) {
$this->queryResult = $this->conn->prepare($sql);
$this->queryResult->execute($params);
}
else {
$this->queryResult = $this->conn->query($sql);
}
return $this->queryResult;
}
}
So, how do i tackle this error?
There is nothing wrong with this code.
Since SyntaxError: JSON.parse is a JS error you should just check what data is passed to it. Check the raw response to your request and do some debugging.
This is probably a problem with your db connection or your $param2 or $param3 conditions are not met.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

SELECT_IDENTITY() not working in php

Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"

Zend Framework 2 inserting into database works fine but still iam getting an error

Here is my model code below,
public function insertme()
{
$sel = new Sql($this->adapter);
$s = $sel->insert('users');
$data = array(
'fname'=>'fisdsds',
'lname'=>'sdsdsdme',
'email'=>'sdsdsds',
'pword'=>'dsdsds'
);
$s->values($data);
$statement = $sel->prepareStatementForSqlObject($s);
$comments = $statement->execute();
$resultset = new ResultSet();
$resultset->initialize($comments);
$result = $resultset->toArray();
//print_R($result);
return $result;
}
it is inserting data into database table users but iam also getting an error SQLSTATE[HY000]: General error what could be the problem?
There's no need to try and make a ResultSet from an insert, it's not going to give you back any resultset data.
public function insertme()
{
$sel = new Sql($this->adapter);
$s = $sel->insert('users');
$data = array(
'fname'=>'fisdsds',
'lname'=>'sdsdsdme',
'email'=>'sdsdsds',
'pword'=>'dsdsds'
);
$s->values($data);
$statement = $sel->prepareStatementForSqlObject($s);
$result= $statement->execute();
//print_R($result);
return $result;
}

Adding subscriber to dotmailer address book

I'm having issues adding a subscriber to a specific addressbook in dotmailer using nusoap. I've no problem adding a generic subscriber to all contacts using the CreateContact method however when I try and use the AddContactToAddressbook method, I just doesn't work.
The if statement used at the bottom returns successful, however nothing exists in the $result variable.
<?php
function subscribe($email, &$result)
{
global $postURL, $username, $password;
$addressBookId = "######";
$contact = array("Email" => $email, "EmailType" => "Html");
$params = array("username" => $username, "password" => $password, "contact" => $contact, "addressbookId" => $addressBookId);
$client = new soapclient($postURL, true);
$error = $client->getError();
$result = $client->call('AddContactToAddressbook', $params);
if($client->fault) {
$rv = false;
} else {
// Check for errors
if($error) {
$rv = false;
} else {
$rv = true;
}
}
return $rv;
}
if(subscribe("test#test.com", $result)) {
echo "success<br />";
print_r($result);
} else {
echo "failed<br />";
}
?>
This code works as is with only changing
$result = $client->call('AddContactToAddressbook', $params);
to
$result = $client->call('CreateContact', $params);
But then the subscriber is not in any particular list. Does anyone know what I might be doing wrong.
p.s. the $addressBookId variable has been blanked out intentionally, I didn't try to run it with '######' as the value in case you were wondering.
And once in production the $result variable will not be returned with the function.
Thanks
use
$result = $client->call('AddContactToAddressBook', $params);
capital B on book

Categories