PHP: replace a "variable" from mysql query (Table's content) - php

I am trying to echo a variable, from a mysql query, like this:
<?php
...//FYI: mysql connection already established
//Table: title
//col: page | title
//row: html | "$domain_name: Welcome"
$page_id = basename(getcwd());
$domain_name = "Name of My Domain";
$sql = "SELECT title FROM mydatabase.title WHERE page = '$page_id' ";
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];
//it outputs: $domain_name: Welcome", instead of "Name of My Domain: Welcome"
?>
What am I doing wrong?
I am trying to replace the "variable [$domain_name] in the table's content for it's php value. -I thought " (double quotes) are supposed to replace the variable with it's value.
PS. I am a beginner
EDIT 2/7/2012, 3:14pm: Forgot to mention. The query works OK. $dba['title'] has "$domain_name: Welcome" as a value. The problem is, it is not replacing $domain_name

I thought " (double quotes) are supposed to replace the variable with it's value.
That works only in case when you specify the string in your code. If the string comes from outside - it doesn't have such magic behaviour.
So the only solution you could go with is:
echo str_replace('$domain_name', $domain_name, $dba["title"]);
Or you could go with some sort of template engine like Twig or Smarty and treat your database value as a template, and your variables as the data.

You can replace it on database level:
$sql = 'SELECT REPLACE(title, \'$domain_name\',\''.$domain_name.'\') as title FROM mydatabase.title WHERE page = '.intval($page_id);
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];
(Note the single quotes)

Related

Error when using while loop in another while loop

I was trying to do a stock recording function which post out product in rows using while loop and the stock count in another while loop but when i run the code it returns error in the second while loop and i'm not sure which part did i went wrong. Need some help here!
Here's the code:
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('EmployeeDB');
$rproduct = "SELECT Product FROM `tbl_user` GROUP BY Product";
$result = mysql_query($rproduct);
while($row1 = mysql_fetch_array($result)){
$prod = $row1['Product'];
echo "<tr><th>$prod</th>";
$rstock = mysql_query('SELECT opening, closing FROM tbl_user WHERE Product = $prod ORDER BY date');
while ($row2 = mysql_fetch_array($rstock)) {
echo "<td>".$row2['opening']."</td>";
echo "<td>".$row2['closing']."</td>";
}
echo"</tr>";
}
Quick solution
Replace this line:
$rstock = mysql_query('SELECT opening, closing FROM tbl_user WHERE Product = $prod ORDER BY date');
With:
$rstock = mysql_query("SELECT opening, closing FROM tbl_user WHERE Product = '$prod' ORDER BY date");
There are two problems with the original line:
You were using a variable inside a single quoted string and that is wrong, it only works with double quoted strings.
the variable $prod needs to be wrapped in single quotes because you are searching for a string, without the quote you were actually telling mysql to search for a row where column product equals the value inside a column which name is whatever inside variabe $prod.
Better solution
Use mysqli or pdo instead of mysql because it is deprecated, and prepare statements instead of just putting variables inside strings.

PHP MySQL: Search database for string (in array) missing results

I am creating a feature which searches a database for a string. The PHP shows no errors using a PHP validator and, if the search term doesn't exist, it returns the correct errors. My problem is that, when searching for the term 'abandon hastily' in the column of the database entitled 'collocation' (which is currently the only entry in the database), no results are returned. Though I can see using phpMyAdmin that this entry does definitely exist.
The string is entered by a user into an input field using the following HTML:
<form action='http://www.murkyfiles.esy.es/search.php' method='GET'>
<center>
<p><label for='search'>Please enter your question as accurately as possible:</label></p>
<p><input type='search' size='90' name='search'></p>
<p><input type='submit' name='submit' value='Find answer'></p>
</center>
</form>
The term entered is searched on the database using the following PHP:
<?php
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
$host = "[HOST URL]";
$username = "[USERNAME]";
$password = "[PASSWORD]";
$database = "[DATABASE]";
$searchlength = strlen($search);
if( !$button )
echo "You didn't submit a keyword";
else {
if( strlen( $search ) <= 1 )
echo "Search term too short";
else {
echo "You searched for <b> $search </b> <hr size='1' > </ br > ";
// Connect to database
$con = mysqli_connect ( $host, $username, $password );
if(!$con) {
die('Could not connect: ' .PDO::errorInfo());
}
mysqli_select_db ( $con, $database );
$search = str_split($search, $searchlength);
$construct = " SELECT * FROM 'coll_test' WHERE collocation LIKE '%$search%' ";
$run = mysqli_query( $con, $construct );
//Fetch and return search results.
if ($foundnum == 0)
echo "Sorry, there are no matching results for <b> $search[0] </b>.
</ br >
</ br > 1. Try presenting your Something is wrong in a more academic manner. Guidance can be found on the majority of University websites without need for registration.
</ br > 2. Try more common words/phrases with similar meaning. This search focuses on colloquialisms - commonly used phrases within a language.
</ br > 3. Please check your spelling";
else {
echo "$foundnum results found !<p>";
while ( $runrows = mysqli_fetch_assoc($run) ) {
$collocation = $runrows ['collocation'];
echo "<a href='$url'> <b> $title </b> </a> <br> $desc <br> <a href='$url'> $url </a> <p>";
}
}
}
}
I have looked at various similar questions and none of them offer solution.
To clarify, the database table column headers are as follows:
collocation | left | right | length | google-results | bing-results | yahoo-results | url-link | wiki | date
There is, so far, only one entry in my database:
collocation = abandon hastily
left = abandon
right = NULL
length = 2
google-results = 24000000
bing-results = 386000
yahoo-results = 385000
url-link = oxforddictionary.so8848.com/search1?word=abandon
wiki = 0
date = [TIMESTAMP]
A quite rewrite, with notes below:
$con = mysqli_connect ( $host, $username, $password, $database );
//$search = str_split($search, $searchlength); ///??? See below
$searchSafe = preg_replace("/[^0-9a-z-_ ]/i","",$search); //example only.
$construct = " SELECT COUNT(*) AS found FROM `coll_test`
WHERE collocation LIKE '%".$searchSafe."%' ";
$run = mysqli_query($con, $construct);
$result = mysqli_fetch_array($run);
print $result['found']." number of results found!"; //for example.
1) You can include the database reference in the MySQLi connection function.
2) str_split returns an array but you are using the result as a string. This is confusing and incorrect, what do you intend to do with this?
$_GET['search'] will always be a string type, so you do not need to use it as an array or any array-based messing around with it.
3) Having outside functions manually returning a number_rows count can be inaccurate, instead use COUNT within the SELECT statment.
4) You forgot to return the result of your actual query! So above I have inserted a mysql_fetch_array result to see the number of results. You also did not define a value for your $foundnum variable.
5) You are mixing PDO with MySQLi, these two connection methods are mutually exclusive. They do not mix.
6) You are wide open to SQL injection and database compromise you need to use Prepared Statements (as well exampled by Saty ) and use something like preg_replace (or another REGEX parser) to remove invalid characters from strings, such as:
$searchSafe = preg_replace("/[^0-9a-z-%_ ]/i","",$search); //example only.
The above would mean only 0-9 or a-z (case insensitive, /i) or -, % or _ are allowed in the string.
7) table or column names ('coll_test') should not be encased in single quotes, instead they shold be encased in backticks, if at all. In MySQL single quotes are for containing data strings only.
Wrap off quotes form table and column name instead use backtick and your code is open for sql injection user prepare and bind statement to prevent it
$search = $_GET ['search'];// get your value
$like = "%$search%";//
$stmt = $con->prepare("SELECT `collocation`,`left`,`right` FROM `coll_test` WHERE collocation LIKE ?");
$stmt->bind_param('s', $like);
$stmt->execute();
$stmt->bind_result($collocation,$left,$right);
$rows = $stmt->num_rows;// check your query return result of not
if ($rows > 0) {
while ($stmt->fetch()) {// fetch data from query
printf ("%s (%s)\n", $collocation,$left,$right);
// fetch data form result set
}
} else {
echo "Sorry, there are no matching results for <b> $search </b>.";
}

PHP Retrieving Data From MySQL After Modifying URL Parameter

I'm building a webpage that retrives data depending on a URL parameter.
There are two possible parameters.
1: id which is retrieved using $_GET['id']
2: name which is retrieved using $_GET['name']
When I am retrieving data using the id parameter it works like a charm since id is always a numerical value and never alphabetical text.
But when attempting to retrieve data using the name parameter I get no results.
The name parameter is checking the database for an article with the articles title being the parameter.
For example the name parameter in a URL would look like so:
http://example.com/safetyarticles/view.php?name=9-clues-to-solving-this-parameter-issue
And in the database the articles name would be: 9 Clues To Solving This Parameter Issue
I've already written some lines to remove the dashes in my url parameter to spaces and then capitalize each word to match the article name, but I'm not getting any results.
This is the code I have written:
$conn = getConnected("safetyArticles");
if(isset($_GET['id'])) {
$articleID = $_GET['id'];
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_id = $articleID");
$article = mysqli_fetch_array($articleQuery);
}
else if(isset($_GET['name'])) {
$articleName = $_GET['name'];
$articleName = preg_replace("/[\-]/", " ", $articleName); // Replace dashes in URL parameter with spaces
$articleName = ucwords($articleName); // Uppercase first letter of each word of URL parameter
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = $articleName");
$article = mysqli_fetch_array($articleQuery);
}
To my knowledge replacing the dashes with spaces and capitalizing each word should make the article_name in the database and $articleName match.
I did add a line of echo $articleName just to see what the output was and the result was 9 Clues To Solving The Mystery Of The Pilot Car which matches the title in the database but the results are not being pulled.
I copied this directly out of the database just to show that the titles are indeed the same: 9 Clues To Solving The Mystery Of The Pilot Car.
I'm at a loss since everything is matching up as it should.
you need '' around the variables in the query:eg '$articleName':
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");
$articleName in your query needs to be quoted like this : '$articleName'. eg
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");

Dynamic MySQL query

I'm trying to create a dynamic sql query that compares my cat column to whatever the user entered in a form. The idea is that I will be able to take a dynamic array of values and then compare them to the cat column. This is what I tried to do:
// Loop to get the array of values from form
$get_arr = $_GET;
foreach ($get_arr as $get) {
$var = "AND cat LIKE $get";
}
// SQL query
$sql = "SELECT * FROM items
WHERE title LIKE 'this'
AND description LIKE 'that'
'%$var%'";
It doesn't work -- $var always show up blank. What would the solution be?
You have several problems.
You're not escaping the input, so you're subject to SQL injection or syntax errors.
You need to put quotes around the LIKE parameter.
You're overwriting $var each time through the loop instead of appending to it.
You're not putting any spaces around the expression.
You're putting % around the whole $var, it should be inside the LIKE parameter.
foreach ($get_arr as $get) {
$get = mysqli_real_escape_string($conn, $get);
$var .= " AND cat like '%$get%'";
}
$sql = "SELECT * FROM items
WHERE title LIKE '%this%'
AND description LIKE '%that%'
%var";

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

Categories