Skip to content
Advertisement

Why does using vsprintf instead of sprintf to format a query string to pass to Laravel’s DB::select cause the return of a non-object?

I am having trouble when using vsprintf instead of sprintf to format a query string I pass to DB::select. I have narrowed the problem down through elimination. At first I attempted to use sprintf to insert a variable into a string. I used that string as a parameter for DB::select:

$query = sprintf("SELECT * FROM test_posts WHERE post_slug = %s;", $post_slug);
$result = DB::select($query);

dd($result);

The result was fine. I modified the code to allow inserting multiple variables into a string:

$table = 'test_posts';
$column = 'post_slug';
$query = vsprintf("SELECT * FROM %s WHERE %s = '%s';", [$table, $column, $identifier_slug]);
$rslt_post = DB::select($query);

//return view('post_viewer', ['arr_post' => $rslt_post] );

echo "<pre>";
print_r($rslt_post);        
dd($rslt_post);

The result was fine and identical for both code variants:

Array
(
    [0] => stdClass Object
        (
            [post_ctr] => 2
            [post_slug] => my-first-post
            [posted_by] => J_Rives
            [date_posted] => 2020-02-03 09:03
            [last_edit] => 2020-02-03 16:54
            [post_body] => Test post #2. Ctr = 2, No title.
        )

)
array:1 [▼
  0 => {#250 ▶}
]

I attempted to return a view with the result object passed as a parameter.
return view('post_viewer', ['arr_post' => $rslt_post] );

The result was the following error message:

FacadeIgnitionExceptionsViewException
Trying to get property 'posted_by' of non-object (View: C:Users7testproject1.0resourcesviewspost_viewer.blade.php)
http://127.0.0.1:8000/posts/my-first-post

The referenced line in post_viewer.blade.php is this:
<h4> {{ $arr_post->posted_by }} </h4>.

Why does it claim that a variable verified by dd and print_r as an array object is a “non-object” from which I attempted to access the “property” called “title”?

Advertisement

Answer

no need of sprintf or vsprintf

$result = DB::select("SELECT * FROM test_posts WHERE post_slug = :slug", ['slug' => $post_slug]);

and fully dynamic

$names = ['test_posts', 'comments'];
$columns = ['post_slug', 'comment_slug'];
foreach($names as $i => $tableName){
     $rslt_post = DB::table($tableName)->where($columns[$i], $identifier_slug);
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement