* if(!empty) retrieves first entry in array and shouldn't be used *
This script searches a database for a url that matches the one submitted by a user in a form. Currently the $query printed by the echo statement works fine in mysql and returns one entry. This script executes and prints the table header, but doesn't enter the while($row =.. ) loop.
Any thoughts or suggestions would be really appreciated. I've used this method before with no trouble so I'm sort of stumped right now.
//1. Query DB for results
$query = "SELECT * FROM projects WHERE projectsurl='".$url."';";
echo "<br>".$query;
$projects = mysqli_query($conn, $query);
// 2. Print Project Results
if(!empty(mysqli_fetch_assoc($projects))){
//Print Project Results
echo "Is this your project?<br>";
echo "<table style=width:'100%'>";
while ($row = mysqli_fetch_assoc($projects)){
echo $tabler . $thh . "Title: <br>" .$row['title'] . $thsp . "No. Rewards: <br>" . $row['rewards'] . $thf . $xtabler;
echo $tabler . $thh . "ID: " .$row['id'] . $thf . $xtabler;
// Echo two rows for the URL Strings because they are longer.
echo $tabler . $thh . "<a href='" . $row['projectsurl'] . "'>Projects</a>" . $thsp . "<a href='" . $row['rewardsurl'] . "'> Rewards " . $thf . $xtabler;
echo "<form id='confirmation' action='../index.php' method='POST'>
<input type='hidden' value='2' name = 'stage'>
<input type='hidden' value='".$row['id']."' name='id'>
<input type='hidden' value='".$row['title']."' name='title'>
<input type='submit' value='Confirm'></form>";
}
echo "</table>";
}else{
//trigger ruby script to search for lost file
echo "Project Not Found. <br>";
}
Oh and the random table stuff is defined elsewhere as
$tabler = "<tr>";
$xtabler = "</tr>";
$thh = "<th><b>";
$thsp = "</th><th>";
$thf = "</b></th>";
$csp = "</td><td>";
$ch = "<td>";
$cf = "</td>";
If there's only one row, then if(!empty(mysqli_fetch_assoc($projects))){ will fetch it and your while loop will not be entered. Instead, to check if a row exists, use mysqli_num_rows($projects).
Also, Reminder, escape your user submitted data before using it in your MySQL query if you haven't already. This can be done by: $query = "SELECT * FROM projects WHERE projectsurl='".mysqli_real_escape_string($conn, $url)."';";
EDIT: Alternatively, prepare your MySQL statements before executing them. This is the preferred method, although both protect you from injections.
Related
I have a page that is running an SQL query. I am displaying information for each row that the query results in. I am now trying to implement a way to update the information for the things being displayed.
My understanding is that in order to get information from one page to another you need to use sessions.
My code is displaying the information from the MySQL tables, then underneath it is giving the user the choice to edit the information in a form then send it to another file
One way of easily doing this is to use <input type="hidden"> so that you can include $row['Toy_ID'] in your form.
Something like this:
$row = $result->fetch_assoc();
while ($row){
echo "Toy Name: " . $row['Toy_Name'] . "<br>" .
"Store Name: . $row['Store_Name'] . "<br>" .
"Cost: " . $row['Cost'] . "";
echo "<form action='update.php' method='post'>" .
"<input type='hidden' name='toyid' value='".$row['Toy_ID']."'>" . // here's the hidden input, which you can call by using `$_POST['toyid']`
"<label>Toy Name: </label><input name='tname'; value='" . $row['Toy_Name'] . "'><br>" .
"<label>Store Name: </label><input name='storename'; value='" . $row['Store_Name'] . "'><br>" .
"<label>Cost: </label><input name='cost'; value='" . $row['Cost'] . "'><br>" .
"<input type='submit' value='Submit'>" .
"</form></div><br><br>";
$row = $result->fetch_assoc();
}
Then change your query to make use of $_POST['toyid'] instead of $_SESSION['toyid']
I am complete newbie to PHP/SQL and all this stuff, also not really skilled with any kind of programming. My problem is that I am currently trying to pull out data from MySQL table on to website, but after finishing the code it pulls out all of the data from my table.
I would love to somehow get to pull out only data from specific table row, based on it's primary key. My current code looks like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rainbow";
$link = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: COuld not connect." . mysqli_connect_error());
}
$sql = "
SELECT name
, nick
, surname
, team
, country
, birthdate
, mouse
, dpi
, keyboard
, headset
FROM players
";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>name</th>";
echo "<th>nick</th>";
echo "<th>surname</th>";
echo "<th>team</th>";
echo "<th>country</th>";
echo "<th>birthdate</th>";
echo "<th>mouse</th>";
echo "<th>dpi</th>";
echo "<th>keyboard</th>";
echo "<th>headset</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['nick'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['team'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['birthdate'] . "</td>";
echo "<td>" . $row['mouse'] . "</td>";
echo "<td>" . $row['dpi'] . "</td>";
echo "<td>" . $row['keyboard'] . "</td>";
echo "<td>" . $row['headset'] . "</td>";
echo "</tr>";
}
echo "</table";
mysqli_free_result($result);
}
else {
echo "Ziadny vysledok a nic nefunguje";
}
}
mysqli_close($link);
?>
To be honest, I am not even sure if this is the right way to do it, but it works and it pulls the data into a HTML table which is not necessary for me, I just wanted to try it. Thanks for answers!
Let's suppose you have a page with this code:
<form action='page2.php' method='post'>
Inform a number:
<input type='text' name='number'>
<input type='submit' value='Send'>
</form>
Save the form above as page1.php
The file page2.php will contain the code that select one register from your table and show the result.
<?php
$id = $_POST["number"];
//The sql command will look like this:
$sql = "SELECT name, nick, surname, team, country, birthdate, mouse, dpi, keyboard, headset FROM players WHERE id = $id";
?>
A couple of things.
Firstly, You would typically keep some of your confidential stuff (database name, userid, password and server name in a separate file (eg. config.php) and you would "include" that file in this file... include ("config.php");
Secondly, in your $sql line you are selecting all of your columns individually and later in the 10 lines after your "while" statement you are selecting them again (for display). I would be calling the whole table in your $sql line with SELECT * from players and I would follow this with a WHERE. As a newbie, your basic retrive from batabase has 3 main words, SELECT (means go and get what you want and in most cases, grab it all with a *) FROM (the table you want to get it from, in your case the table is players) and WHERE (this is your selection criteria... id > 50...colour = "blue"... whatever you want). When pushing data to the DB you would use SET and UPDATE but when retrieving... SELECT, FROM, WHERE.
Your "while" statement will simply do your $sql statement (select, from, where) and return results until it runs out of records
Good luck Newbie
gri2a
When I create/edit post to my website, and when I use html tags (either type it by my self or using WYSIWYG editor (in this case nicEdit, but I've used different one - same problem)) it does not show anything on the page.
to be more specific: I have article container which imports php code, which than iterates through the db table and echo posts. This is the code:
<h3>Wydarzenia</h3>
<?php
//collects data from table "events" and sort it by "id" date in descending oreder
$event_table_data = mysqli_query($db_con, "SELECT * FROM events ORDER BY id DESC")
or die(mysqli_error());
//puts the data from "events" into an array
$event_content_array = mysqli_fetch_array($event_table_data);
//makes variables from table columns
$id = id;
$title = title;
$happeninng_date = happen;
$created_date = created;
$content = content;
$author = author;
//add new post button
if((isset($_SESSION['sess_wizardrights'])) && ($_SESSION['sess_wizardrights'] == true)){
echo "<a class='e_event_addpost_link' href='./index.php?link=add_post'><button class='e_event_addpost_button' type='button'>Dodaj nowy post</button></a>";
}
do{
//echo each event for main event article
echo "<span class='b_events_span' id='" . $event_content_array[$id] . "'>";
echo " <a class='b_events_anchor' id='" . $event_content_array[$id] . "'></a>";
echo " <h2 class='b_events_title'>" . $event_content_array[$title] . "</h2>";
if((isset($_SESSION['sess_wizardrights'])) && ($_SESSION['sess_wizardrights'] == true)){
echo "<form class='b_events_edit_form' name='edit_post' action='./index.php?link=edit_post' method='post'>";
echo " <input type='hidden' name='id' value='" . $event_content_array[$id] . "'> ";
echo " <input class='e_events_edit_submit' type='submit' value='Edytuj wydarzenie'>";
echo "</form>";
}
echo " <div class='fb-share-button' data-href='http://www.zhppgkaberdeen.co.uk/index.php?link=events#" . $event_content_array[$id] . "'></div>";
echo " <p class='b_events_happening_date'><i>Data wydarzenia: " . $event_content_array[$happeninng_date] . "</i></p>";
echo " <p class='b_events_content'>" . $event_content_array[$content] . "</p>";
echo " <p class='b_events_created_date'>Utworzono: " . $event_content_array[$created_date] . "</p>";
echo " <p class='b_events_author'><b>Czuwaj!</b><br/>" . $event_content_array[$author] . "</p>";
echo "</span>";
}while($event_content_array = mysqli_fetch_array( $event_table_data ));
?>
When I add tags like <img> for instance with alt="" parameter it completely ruins web page. What I mean by that is that the article container is not shown at all (I've checked that with firebug) as well as everything after the article tag (like footer for instance). What is even more strange is that this: alt="text" did not break the page but every other random word does, how ever it does not show the "text" at image at all.
Similar thing happen when I tried to create table within the post and title or target parameter, I cant remember which one.
I have tried to use htmlentities($event_content_array[$content]), htmlspecialchar($event_content_array[$content]) and mysqli_real_escape_string($do_con, $event_content_array[$content]) -> non of this helped.
Is there a way to fix that or I just need to give up using this tags/parameters?
Thank you for any help or explanation
if you are using e.g echo "<img alt="text">";try to escape the " such as alt=\"text\"
I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.
i have this quick issue please.
I have this code here which permits me to extract a user name and a photo, and when the name is clicked it takes me to this hostess.php file, well, i need to pass the id variable to the hostess.php and save it, in order to get information only for that id..
Here is the code:
while ($row = mysql_fetch_array($query)) {
echo "<div id='photo'>";
echo "<div id='picture'>";
echo "<td> <img src=foto/photo1/".$row['photo'] . "></td>";
echo "</div>";
echo "<div id='text'>";
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
echo "</div>";
echo "</div>";
}
How can i just get the id and then how can i save it to the $id variable
Thanks
The table structure is like this:
The table name is called hostess and the field i need to retrieve from hostess is the [id]
Change the line:
echo '<td><a href="hostess.php">'. $row['first_name_en'] .
" ". $row['family_name_en']."</a></td>";
to this:
echo '<td><a href="hostess.php?id={$row[id]}">'. $row['first_name_en'] .
" ". $row['family_name_en']."</a></td>";
and in hostess.php, use this to extract the value:
$id = $_GET['id'];
EDIT
Here is another method to pass variable as POST. Again, change the aforementioned line to:
echo '<td><form method="POST" action="hostess.php">' . "<input type='hidden'
name='id' value='{$row[id]}' />" . "<input type='submit' value='" .
$row['first_name_en'] . " " . $row['family_name_en'] .
" /></form></td>";
You can use CSS to style that button as simple text too. And the value can be retrieved in hostess.php as follows:
$id = $_POST['id'];
Add/change this in your code:
$personID = $row['id']; #or whatever the field name is
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
The addition of "?personID='.$personID will send the value in the GET statement, or within the URL.
On the receiving page get the value that way:
$personID = $_GET['personID']+0; #add zero to force a numeric value--be sure to scrub your data!
#be sure to do other validation if needed!