-1

I have SQL query in Laravel as such:

$PDO = DB::connection('mysql')->getPdo();
$sql = <<< SQLEND
SELECT EXISTS(SELECT * FROM tpalautus where student_id = $id AND hnro=$num) ;
SQLEND;

$allsql = $PDO->prepare($sql);
$allsql->execute();
$result = $allsql->fetchAll((\PDO::FETCH_OBJ));
dd($result);

dd shows me that:

array:1 [▼
  0 => {#345 ▼
    +"EXISTS(SELECT * FROM tpalautus where student_id = 4 AND hnro=1)": 0
  }
]

My problem is that I wish to do if statement on this result, check if it is 0 or 1, how do I do this ? I find it quite difficult to select this since objects key is SQL query statement. For example $result[0]->KEY_HERE is not working with such a long string Query statement.

Can I somehow choose what I want as that Key name? Or any other way?

Jeekim
  • 543
  • 5
  • 15
  • is there any reason you're not using Eloquent ORM and instead exposing a SQL injection vulnerability in your code? – Salim Djerbouh Jun 28 '20 at 18:02
  • 1
    its a school task, we did Eloquent first and then we have this exercise where you do SQL "manually". – Jeekim Jun 28 '20 at 18:04
  • I`m not sure I fully understand the expected result, but have you check the documentation for EXISTS https://www.w3schools.com/sql/sql_exists.asp – perelin Jun 28 '20 at 21:16
  • Also that might be a pointer: https://stackoverflow.com/a/41490188/55049 – perelin Jun 28 '20 at 21:19

2 Answers2

1

You can use get_object_vars to convert the object into an array then flip the keys with their values for easy access

$vars = get_object_vars($result[0]);
$exists = array_values($vars);
if ($exists[0]) {
  dd('true');
}

Hope this helps

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
  • thank you! I didnt know I could flip like that. I also found alternative solution to not use exists and just run normal select with limit 1, and then check if count() > 0 – Jeekim Jun 28 '20 at 18:27
0

I worked out alternative way, dont need to use EXISTS, just running a query with select

SELECT * FROM tpalautus where student_id = $id AND hnro=$num limit 1;

and then i check if count($result) > 0

Jeekim
  • 543
  • 5
  • 15