I'm having trouble with my php code. I have a table in my DB and every entry has a name, type, location etc. The basic idea is that after entering the name from the previous page (that's why there's a POST variable at the start of the code), you get transfered to this page and it prints the corresponding type. The problem is that even though I'm sure the code is correct and I've tried a few different solutions (I've been searching for a while in the forum), I can't print the type variable.
<?php
$k = $_POST['sub1'];
$con = mysqli_connect("localhost","root","","qr code");
$query = mysqli_query($con, "SELECT type FROM array1 WHERE name ='".$k."'");
while($row = mysqli_fetch_assoc($query)) {
echo $row['type']; }
?>
Any ideas? It's probably a very simple solution, but I'm totally stuck now so I'm sorry if it's too basic :P
Related
I am in a little bit in doubt, if I am on the correct path here. I have a mysql database, where I have login details of users. I am making a profile page, where I would like the informations on a user is shown to the user. I am now trying to return the firstname there is a column in the database. Am I on the correct path with this code?
<td>
Firstname
<?php
$stmt = $mysqli->prepare("SELECT firstname FROM login");
$stmt->execute();
$fname = null;
$stmt->bind_result( $fname);
while($stmt->fetch()) {
$firstname = // Code here
echo $firstname;
}
$stmt->close();
$mysqli->close();
?>
</td>
Update:
I tried to make the code a little bit smaller. This code actually retrives users, but it is all the users in the database, and not only the user I am logged into with. Should the SELECT query be asigned with the primarykey, if I only need the firstname on the current user I am logged in as?
<td>
Firstname
<?php
$sql ="SELECT firstname FROM login;";
$res = $mysqli->query($sql);
//print($res);
if($res){
while($row = $res->fetch_assoc()){
echo $row['firstname'];
}
}
?>
</td>
You are on the correct path but you need to assign your array to a variable so you can print adding your column name in the scope and remove the bind of $fname
//$stmt->bind_result($fname);
while($column = $stmt->fetch()) {
$firstname = $column['firstname'];
echo $firstname;
}
Or you can just use the variable you bind before
$stmt->bind_result($fname);
while($stmt->fetch()) {
echo $fname;
}
You could optimize your query and limit tresult to only one user by adding a WHERE condition to your query, you can use user ID for example
SELECT firstname FROM login WHERE userid = 1
If you're playing around with PHP and trying to learn how things work, you're on a great path. If you're planning on deploying this code to the internet, you have a few issues:
Your markup seems off. Why are you putting all of the first names in a single <td>?
You shouldn't have a SQL query happening inside of a markup. What if you want to show results from a cache or a text file some day? Ideally you wouldn't even mix PHP and HTML. Some folks use PHP's built-in templating abilities, but it's generally preferred to use a template language like jade or twig.
Your code alignment isn't consistent.
But if you're just seeing what PHP can do, good job. Keep trying stuff out. It's the best way to learn for most people. Others like reading a book, then trying stuff.
I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples
I have a database and I am using it to create a seminar page. It holds the seminar information and then when my php page is opened it reads the entries in the database and displays them.
however I am having an issue. There is a field in my entry form for the abstract of the seminar. Sometimes they have multiple paragraphs. When I enter multiple paragraphs into the html form textbox it looks fine. Also I checked what it looks like once it has been added to the mysql database, it looks fine there as well. The problem is when I open my more info page and it displays the abstract. There are no line breaks or tabs. I have been searching and it appears to be an html issue.
I know what the issue is, but I dont know how to fix it. Is there an html command that will render the line breaks and tabs? or perhaps a php command? Any help I could get would be greatly appreciated. Thank you in advance.
edit: to make this post a good reference for others ill post my code
$data = mysql_query("SELECT * FROM seminars WHERE ID = '$ID'"
while($info = mysql_fetch_array( $data ))
{
echo $info['abstract'] . "\n "; ?>
}
However I used the nl2br function that was recommended and it worked perfectly, it was really simple. here is the appended code:
$data = mysql_query("SELECT * FROM seminars WHERE ID = '$ID'"
while($info = mysql_fetch_array( $data ))
{
echo nl2br($info['abstract']) . "\n "; ?>
}
The function you are looking for is nl2br(). this will convert all new line characters to tags and create the html space you are looking for.
Something like:
echo nl2br($descriptionText);
//$descriptionText being the paragraphs you pulled from the database.
I wonder whether someone may be able to help.
I posted a similar message to this little three days ago, but I think that my explanation of the problem wasn't particualrly good so I thought I'd start afresh. I will say that I am new to programming in PHP so please bear with me.
I have three mySQL tables, 'userdetails', 'detectors' and 'detectorsearchheads' with the following fields:
userdetails
userid
name
detectors
userid
detectorid
detectordescription
detectorsearchheads
userid
detectorid
detectorsearchheadid
detectorsearchheaddescription
What I would like is to have a drop down menu on my HTML form that through PHP, shows the list of detectors applicable to the user that is logged on. In turn I would then like another drop down menu that again is user specifc, but additionally only shows the detector search heads applicable to the value selected from the first drop down menu.
I appreciate that there may be other ways to do this but I am more comfortable with PHP.
I just wondered whether someone could possibly please show me what I need to do to get this to work. As I said earlier I am fairly new to PHP, so the simpler the better.
Many thanks and regards
Chris
UPDATED CODE
<?php
mysql_connect("hostname", "username", "password") or die("Connection Failed");
mysql_select_db("databasename")or die("Connection Failed");
$query = "SELECT * FROM detectors WHERE `userid` = '1' ORDER BY 'detectorname' ASC";
$result = mysql_query($query);
?>
<select name="detectorname">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['detectorname'];?>"> <?php echo $line['detectorname'];?> </option>
<?php
}
?>
</select>
Check this tutorial for example.
Before that you have to generate the html and js code with php. Basicly, get the data from database, and generate needed list. For example:
echo "<li>".$dataFromDatabase."</li>";
You will need CSS/JS to display the Drop Down Menu. With PHP you will prepare the text to be displayed.
After the mysql query, the result should be echoed in appropriate format.
For Eg. if your CSS displays list items(li) as menu, you need to do what 'Waltsu' said.
$result = mysql_query("..."); //your specific query
while ($row = mysql_fetch_assoc($result))
{
echo '<li>'.$row['detectordescription'].'</li>';
//so on
}
I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}