0

I have a general question regarding the assigning of sql results to a arrays. What should I do when I want to assign some results to an array and when I am joining two or more tables and some columns got the same name:

Example:

$sqlExample = "select u.first_name, o.first_name from tbl_user u join tbl_owner o on u.user_id = o.user_id where u.user_id = $user_id;";
       ...
$userFirstName[$var] = $result['first_name'];
$ownerFirstName[$var] = 

I know, that this is not a great example, but I hope that you are understanding my question.. I thought I could use something like the table prefix for the results, but it didn't worked.

-- Just an example not the code I am using/

4
  • Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe! Commented Jul 12, 2017 at 12:55
  • for example: select i.first_name uFirst_name, o.first_name oFirstname,... Commented Jul 12, 2017 at 12:55
  • @Jan simple use alias field name Commented Jul 12, 2017 at 12:56
  • Hi Jay, yes I know - just an example. In my project I am using something like: $stmt = $db->prepare('update first_name set name = ? where id = ?'); $stmt->bind_param('si',$name,$id); $stmt->execute(); Commented Jul 12, 2017 at 12:58

2 Answers 2

2

Alias your columns in the results:

select u.first_name as user_first_name, o.first_name as owner_first_name from ...

Then use those aliases in your code:

$userFirstName[$var] = $result['user_first_name'];
$ownerFirstName[$var] = $result['owner_first_name'];
Sign up to request clarification or add additional context in comments.

Comments

0
$sqlExample = "SELECT
  u.first_name AS user_first_name,
  o.first_name AS owner_first_name
FROM tbl_user u
  JOIN tbl_owner o ON u.user_id = o.user_id
WHERE u.user_id = $user_id";

$result['user_first_name'];
$result['owner_first_name'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.