Martin Sholev Martin Sholev - 6 months ago 16
SQL Question

Why when i enter news(asdasd) title doesn't show news content, but if change title with number works?

:)
Okay, lets say title is ExampleTitle


news.php


Doesn't work so I'll change my title to another.

$user = new User();
$news = $user->ShowNews(ExampleTitle);
echo '<pre>';
var_dump($news);
echo '</pre>';


New title: 22(works)

$user = new User();
$news = $user->ShowNews(22);
echo '<pre>';
var_dump($news);
echo '</pre>';


ShowNews:


public function ShowNews($title) {
$get_news = $this->_db->query('SELECT * FROM news WHERE title = ' .$title);
return $get_news->results();

}


If the title is a number/numbers work, but if it is letter/letters/word/words does not work.

Answer

That's because strings need to be quoted:

("SELECT * FROM news WHERE title = '$title'");

Don't worry about it either being an integer or a string, the data interpreter will compensate for it.

You can use this for both of the possible instances.

More on string literals if using MySQL. The API used to connect with is unknown.


Edit:

As noted in comments, your code is susceptible to an SQL injection.

Read the following references:

Since the question was tagged as PDO, you can use a prepared statement which runs off Windows server also, should that be the platform you are working under:

Here is another reference link if you are running under a Windows OS: