I have the following code:
$indtag = '';
foreach($pretag as &$indtag) { //cycles through tags, puts quotes into check by tag
$quote = mysqli_query($mysqli, "SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'");
while($row = mysqli_fetch_assoc($quote)) {
echo $row['$indtag'];
echo $row['id'];
}
}
The table has fields for ids, quotes, then an individual column for each tag (ang for anger being an example). pretag is an array full of tags (rom is romance, ang is anger, dece is deception) that I'm running through, trying to find quotes with those IDs and tags. The statement works fine in SQL when I run it with ang, it selects the IDs fine, but when I try to select the column/field for a tag using a variable, nothing comes back. Any ideas?
You're using the variable $indtag where you should be using the column name indtag:
SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'
^ ^
And as #tadman points outs, don't do it this way, use mysqli_stmt_bind_param with a prepared statement or you are in for a wild ride.
This line in your code doesn't need quotes.
echo $row['$indtag']; // Won't work
echo $row[$indtag]; // Will work
Related
I'm trying to get all records from db using getRows method, to achieve that I need to implode special characters.
In previous function, to get $ids I used:
foreach ($ids as &$id) $id = (int)$id;
$rows = $this->db->getRows('SELECT name, id FROM database WHERE id IN ('.implode(',', $ids).')');
if (count($rows)) {
foreach ($rows as $row)
{
$ret[$row['id']] = $row['name'];
}
}
but in my next function I need to use name to search for records.
Because name is in single quotes 'name' I tried making it like this:
foreach ($names as $name) $id=(int)$name;
$rows = $this->db->getRows('SELECT name, is_active FROM database WHERE name IN ('.implode(',',$names).')');
if(count($rows))
{
foreach ($rows as $row)
{
$ret[$row['name']] = $row['is_active'];
}
}
it doesnt solve the problem, it just crashes. So I tried changing it a bit with separating it with double quotes:
$rows = $this->db->getRows("SELECT name, is_active FROM database WHERE name IN (" .implode(',',$names) .")");
still getting same error database query error.
and I dont know really what to do next. I believe I cant pass that many quotes inside of a implode.
Query should look like this: SELECT name, is_active FROM database WHERE name IN ('name1', 'name2', 'name3')
I tried to follow PHP: implode - Manual with same error results.
Switching between single or double quotes like you did, doesn't change the fact that you did not add any quotes around the individual name values at all. These quotes are the string delimiters the PHP syntax requires, but you have not added any quotes around the names in your implode yet, which the SQL syntax requires.
And implode only inserts the separator between the values - so the quote character before the first, and the quote character after the last item, still need to be added.
You want something like
'SELECT name, is_active FROM database WHERE name IN ("'.implode('","',$names).'")'
which will produce
SELECT name, is_active FROM database WHERE name IN ("a","b","c")
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
this ought to be simple but am yet to find an answer for it (i have searched the questions in stackoverflow). am on php and i have a table books on mysql.
What i want is a list displayed in my webpage with these specifics on a table created by php. I know the mysql code:
SELECT title FROM books WHERE category='currently reading'
applying that on php has brought this error, Parse error: syntax error, unexpected 'currently' (T_STRING)
Here is my php code:
<?php
include('include/databaseconnection.php');
include('include/insertingbooks.php');
// selecting data
$result = mysql_query ('SELECT title FROM books WHERE category='currently reading'';);
//("SELECT title FROM books WHERE category LIKE $currently");
//opening table tag
echo "<table border = 1px>";
while ($data = mysql_fetch_array($result)) {
// printing table row
echo'<tr>';
echo '<td>'.$data['title'].'</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
?>
If i decide to leave out WHERE clause, it works perfectly except it displays all the books.
The options i have tried already
using WHERE category LIKE $category while setting up a variable $category = "currently reading"; but it dint work.
trying to link it to the form i got the the values of category from by adding include('include/insertingbooks.php'); (which contains $category =$_POST ['category'];) and trying to put $category.
using WHERE not but it didnt work at all.
You have bad quotes and an extra semi-colon here -
$result = mysql_query ('SELECT title FROM books WHERE category='currently reading'';);
Change to this (note the double quotes) -
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'");
In addition, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO.
You should also add MySQL error checking to your queries and connections.
Using or die(mysql_error()) to mysql_query().
For example:
$result = mysql_query ("SELECT title
FROM books
WHERE category='currently reading'")
or die(mysql_error());
Which would have caught and displayed the syntax error.
there is only quotes problem
Please replace your query to:
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'";);
Please note you can not use same quotes eg. If you are using double quotes then use single quotes inside and if single quotes then double code inside
Use this code:
<?php
include('include/databaseconnection.php');
include('include/insertingbooks.php');
// selecting data
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'");
//("SELECT title FROM books WHERE category LIKE $currently");
//opening table tag
echo "<table border = 1px>";
while ($data = mysql_fetch_array($result)) {
// printing table row
echo'<tr>';
echo '<td>'.$data['title'].'</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
?>
I have an existing recordset that retrieves all the information from a table in mysql called $rrows. What I am hoping to do is to use this existing recordset within a new mysql query.
For example I have the following line that retrieves the "product code" from one table:
<?php echo $rrows['productcode']; ?>
I am trying to then gather the respective images from a new table using this productcode by something similar to:
<img src="<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnimages WHERE productcode='$rrows['productcode']'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>">
Can this be done? Originally I was going to LINK tables together to get all the information, but this doesnt work as some of the product codes in the main do not have corresponding data in the 'furnimages' table.....
Thanks in advance!
JD
sprintf() is your best friend here.
$sql = <<<sql
SELECT * FROM furnimages
WHERE productcode=%d
sql;
$result = mysql_query(sprintf($sql, $rrows['productcode']));
So, %d is the placeholder in the string to swap in the second argument in the call to sprintf();
%d denotes an integer placeholder; if $rrows['productcode'] is a string, use %s.
This is better than simply quoting value of the variable as it adds a type constraint which reduces the risk of nasty sql injection.
It also makes it eminently more readable.
Check out the PHP Data Objects extension, though, because that really is the only way forward for this type of thing.
I do not think that this has been posted before - as this is a very specific problem.
I have a script that generates a "create table" script with a custom number of columns with custom types and names.
Here is a sample that should give you enough to work from -
$cols = array();
$count = 1;
$numcols = $_POST['cols'];
while ($numcols > 0) {
$cols[] = mysql_real_escape_string($_POST[$count."_name"])." ".mysql_real_escape_string($_POST[$count."_type"]);
$count ++;
$numcols --;
}
$allcols = null;
$newcounter = $_POST['cols'];
foreach ($cols as $col) {
if ($newcounter > 1)
$allcols = $allcols.$col.",\n";
else
$allcols = $allcols.$col."\n";
$newcounter --;
};
$fullname = $_SESSION['user_id']."_".mysql_real_escape_string($_POST['name']);
$dbname = mysql_real_escape_string($_POST['name']);
$query = "CREATE TABLE ".$fullname." (\n".$allcols." )";
mysql_query($query);
echo create_table($query, $fullname, $dbname, $actualcols);
But for some reason, when I run this query, it returns a syntax error in MySQL. This is probably to do with line breaks, but I can't figure it out. HELP!
You have multiple SQL-injection holes
mysql_real_escape_string() only works for values, not for anything else.
Also you are using it wrong, you need to quote your values aka parameters in single quotes.
$normal_query = "SELECT col1 FROM table1 WHERE col2 = '$escaped_var' ";
If you don't mysql_real_escape_string() will not work and you will get syntax errors as a bonus.
In a CREATE statement there are no parameters, so escaping makes no sense and serves no purpose.
You need to whitelist your column names because this code does absolutely nothing to protect you.
Coding horror
$dbname = mysql_real_escape_string($_POST['name']); //unsafe
see this question for answers:
How to prevent SQL injection with dynamic tablenames?
Never use \n in a query
Use separate the elements using spaces. MySQL is perfectly happy to accept your query as one long string.
If you want to pretty-print your query, use two spaces in place of \n and replace a double space by a linebreak in the code that displays the query on the screen.
More SQL-injection
$SESSION['user_id'] is not secure, you suggest you convert that into an integer and then feed it into the query. Because you cannot check it against a whitelist and escaping tablenames is pointless.
$safesession_id = intval($SESSION['user_id']);
Surround all table and column names in backticks `
This is not needed for handwritten code, but for autogenerated code it is essential.
Example:
CREATE TABLE `table_18993` (`id` INTEGER .....
Learn from the master
You can generate the create statement of a table in MySQL using the following MySQL query:
SHOW CREATE TABLE tblname;
Your code needs to replicate the output of this statement exactly.
I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';