Using PHP variable variables in SQL query - php

Sorry for this question to be a "can you fix it" one, but this little bit of code has been confusing me for a while now.
I'm basically making a table with a bunch of rows and columns and in each one I have a slightly changing SQL query. To make it a bit easier instead of typing all that out I made this bit of script but it is starting to get a bit complicated so can any of you manage to get it correct?
echo '<td background="images/map/';
$tile = mysql_fetch_array(mysql_query("SELECT image FROM map WHERE horizontal = ${'mapPiece' . $mapPieceCount . [0]} AND verticle = ${'mapPiece' . $mapPieceCount . [0]}"));
echo $tile[0];
echo '.png"></td>';
Thanks, Stanni

Assuming I interpreted this right, the [0] needs to go outside of the curly braces:
echo '<td background="images/map/';
$tile = mysql_fetch_array(
mysql_query(
"SELECT image FROM map WHERE horizontal = ".
${'mapPiece' . $mapPieceCount}[0].
" AND verticle = ".
${'mapPiece' . $mapPieceCount}[0]
)
);
echo $tile[0];
echo '.png"></td>';

First of all, you can't append the array index [0] like that, like you're concatenating on a string. Overall, it would be much easier if you just added a few extra lines to make things neater:
$currentPiece = 'mapPiece' . $mapPieceCount;
echo '<td background="images/map/';
$query = 'SELECT image '.
'FROM map '.
'WHERE horizontal = '.${$currentPiece}[0].' '.
'AND verticle = '.${$currentPiece}[0];
$result = mysql_query($query);
$tile = mysql_fetch_array($result);
echo $tile[0];
echo '.png"></td>';

Related

Finding pattern according to variable content

I would like to do something quite simple but I dont know the right code in php.
I have a variable $go which content is GO:xxxxx
I would like to query that if the content of a variable has the pattern "GO:" and something else, echo something, but if not, echo another thing
I want to declare an if statement like:
if (preg_match('/GO/', $go) {
echo "something";
}
else {
echo "another thing";
But I cannot make it work...
I want to embed this statement between this portion of my script:
$result = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where go_id like '%" . $go . "%'");
$items = mysqli_fetch_assoc($result);
echo "<br/>";
echo "<b> The total number of genes according to GO code is:</b> " . $items['total'];
mysqli_free_result($result);
$result2 = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where db_object_name like '%" . $go . "%'");
$items2 = mysqli_fetch_assoc($result2);
echo "<br/>";
echo "<b>The total number of genes according to GO association is:</b> " . $items2['total'];
mysqli_free_result($result2);
As it is right now, the variable $go can have a value like GO:xxxx or a random sentence, and, with this code, I get two strings, one with value 0 and another with value according to the total apperances matching $go content.
What I want is to declare an if statement so that it just prints one string, the one that has the number of matches according to $go content, but not both.
Any help?
Use strpos():
if (strpos($go, 'GO:') !== false) {
echo 'true';
}
Try this
echo (!strpos($go, 'GO:')) ? "another thing" : "something";
Will surely work

MySQL collecting results regardless of spaces

I have a small application which I have collecting user input and returning a set of results based on the input. The input is a postcode so for example, pl4 7by. Which has a space between it. This is the format of which the data is stored in. I wish to have applicable postcodes returned from the search even if a user inputs without the space between or multiple spaces.
This is currently what I have.
<?php
$input = $_GET["input"] . "%";
try{
$handler = new PDO();
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$stmt = $handler -> prepare("
SELECT * FROM `LSOA_postcodes` WHERE postcode LIKE :input LIMIT 20
");
$stmt -> execute([
":input" => $input
]);
echo "<table>";
echo "<tr><th>Postcode</th><th>LSOA Code</th><th>LSOA Name</th></tr>";
while($row = $stmt -> fetchObject()){
echo "<tr>";
echo "<td>", $row -> postcode, "</td>";
echo "<td>", $row -> code, "</td>";
echo "<td>", $row -> name, "</td>";
echo "</tr>";
}
echo "</table>";
This is functional and returns the results regardless of case. I could store the data with no spaces, but I wish to have the correct format display to the user.
UPDATE
Just had a sudden thought and came up with this:
SELECT * FROM `LSOA_postcodes` WHERE REPLACE(postcode, ' ', '') LIKE REPLACE(:input,' ', '') LIMIT 20
This works as planned from first sight. Is there any problems that I cannot see with this?
Depending on the size of LSOA_postcodes, you may encounter performance problems using REPLACE as in the above 2 answers because it is unlikely to use index scans.
I would check the $input to see if it contains a space and add one if its length is > 3 - all in php then let the SQL do the search as in the original question.
You could trim the spaces on both sides of the = sign:
SELECT *
FROM `LSOA_postcodes`
WHERE REPLACE(postcode, ' ', '') LIKE REPLACE(:input, ' ', '')
LIMIT 20
Notes:
You'll use any benefit on an index on postcode, if you had one.
I stayed with the like operator like OP suggested, although since there are no wild cards here, a simple = should do the trick - Did not notice the use of % online 2, as per comments below.

php replace database result with an image

This is the first time I have ever posted a question. I am a newbie, and I hope I get all the formatting correct in this message. I love stack overflow. It has helped me get through many challenging situations. But this one has me stymied.
I would like to replace a MySQL database result with an image. I have a plant database that I'm querying to show lists of plants. My results table consists of the plant type, the botanical name, the common name, and whether it is a native plant.
The result for the native plant comes in from the database as the letter 'y' (for yes). I would like to replace that 'y' with an image of an oak leaf. The code I'm currently using displays the oak leaf on all plants, not just the ones that are native plants.
What to do? I feel like I need to insert an if statement in the while loop, but it never works when I try it. I've tried tons of different solutions for a few days now, and would like to ask for help with this.
Here's the latest code I've got that displays the image for every plant, not just the natives:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$native_image = $row['native'];
$image = $native_image;
$image = "images/oak_icon.png";
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}
I hope I understood your question.
Some of rows in MySQL have $row['native'], that are equals 'y'. If it is so, then you are on the right way - you have to put an if statement in your loop.
Try it
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
if ($row['native'] == "y") {
//we show our image
$image = "images/oak_icon.png";
} else {
//we don't have to show our image
$image = "";
}
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}
And where is your IMG tag? =)
For the future: In my Projects, if I want to save the information about image, that belongs to the row in MySQL, I just save the name of the picture, where it has to be, and if not, i save the name of empty 1x1 PNG image (usual "blank.png"). If you put blank.png in an IMG tag, that has fixed height and width, so IMG takes just the place on your page.
I hope I helped you, and this is my first Answer! =)
P.s. sorry for my english...
Explosion Pills is correct. You will need to check if the $row['native'] is 'y' then set the image html to whatever is required. Hope this helps.
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$image='';
if($row['native']=='y'){
$image = '<img src="images/oak_icon.png" />';
}
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}

Selecting a Column from a Row from a previous Query

I'm really sorry if this is a simple fix but I'm completely stumped, probably suffering from a temporary block.
Anyway, my predicament goes like this, my website has a page that includes events, I, of course, have an events table which has the following fields:
EventID
EventName
EventStart
EventEnd
EventDesc
Now my first query, is to make sure I collect all events that haven't ended yet. Make sense?
I am then doing a for which looks like this:
for($i=0;$i<$numr;$i++) - $numr is defined as - $numr = mysqli_num_rows($sql) and you can guess what $sql is? Just to be safe: $sql = mysqli_query($link, "SELECT * FROM events WHERE EventEnd >= NOW()")
Inside this for loop, I intend to create multiple <option> tags for however many events there are. So far so good, it looks like this: echo "<option id='" . $i . "' name='" . $i . "' value='" . $i . "'>
That's where my problem is, I know need to get the EventName of the FIRST row that was returned from the sql query. I am unsure of how to do this? My initially thought was to use an array and store the names there, however, I am not 100% familiar with arrays in php.
Is there a way you guys can help me out here? Again I'm really sorry if this is just a basic function I need to use or something but I'm having real problems right now.
Thanks so much guys!
Mike.
See fetch_assoc doc
Instead of
for($i=0;$i<$numr;$i++) {
//echoing options
}
do
while($event = $sql->fetch_assoc()) {
echo "<option id='" . $event['EventID'] . "' value='" . $event['EventName'] . "'>";
}
Outside your for loop: $first name = null;
Inside your loop:
if(empty($first_name))
$first_name = $row['EventName'];

php link from mysql

I am revisiting php and mySQL from a long time off.
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href=\"$row_results['Username'],.php\">';
echo '$row_results['Username'],'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
What I am trying to do is echo out the link from the results the link is in the form username.php the username is stored in the database.
I have used single quotes and double quotes with escaped /" in but get different errors I know its going to be something as simple as a ; or " .
If you could be as kind to explane what is wrong abd if there is a better way to do this?
The query is correct and the commented out code also works on its own.
Thanks
You cannot parse variables through single quotes:
echo '<a href=\"$row_results['Username'],.php\">';
use
echo '<a href="'.$row_results['Username'].'">';
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href="'.$row_results['Username'].'php">';
echo $row_results['Username'].'\'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
Looks to me like the concatenation of your html string and the username is incorrect.
Currently, your string that you are writing to the page is
<a href=\"$row_results['Username'],.php\">
What you need to be doing is joining the html with the value coming out from the database.
This can be done like so:
echo '<a href=\"'.$row_results['Username'].'.php\">';
echo $row_results['Username'].'\'s overview </a><br/>';
Notice the '.' to concatenate two potions of the string, and the escapement of the apostrophe in the 's
Here are your errors :
Even though you are using DISTINCT in your SQL Query, there might be multiple entries, so you must use a while loop.
You had a comma in there (probably by typo).
You need to escaping the php variable.
So after doing the above, this is what it should be.
while ($row_results = mysql_fetch_assoc($result)) {
echo '<a href="' .$row_results["Username"]. '.php">';
}
try:
echo '<a href="'.$row_results['Username'].'.php">';
echo $row_results['Username'].'\'s overview </a><br/>';
Seems like you got pretty mixed up with the " and ' there. You should really avoid using anything other than ' - it will only bite you on the long run.
Also: You concatenate with ., not with ,.
mysql_select_db($database_conn, $conn);
$query = sprintf('SELECT DISTINCT Username FROM Entries ');
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
do {
$name = $row_results['Username'];
echo $name.'<br/>';
echo '<a href="'.$name.'.php">';
echo $name.'\'s overview </a><br/>';
} while ($row_results = mysql_fetch_assoc($result)); ?>

Categories