I have this page thats a quick over view of the logged on users profile, along with some editing functions, so to avoid confusion I'm going to post all of the code, just ignore the html.
In the start of the code I'm retrieving the users information, and then storing it into an array called $row. Later on down the code, I'm retrieving rows from a seperate table, and I want to store those into an array aswell ($postRow). But I just figured out through reading that you can only preform one SQL query per page without running code that I, quite frankily don't understand, and the only tidbits of code that I found regarding that issue printed the information directly onto the page, I couldn't find any on how to store them both into arrays. Can someone help me regarding this issue? I'm really between a rock and a hard place.
<?php
include('header.php');
if (isset($_SESSION['username'])){
require 'connect.php';
$user = $_SESSION['username'];
$query = mysqli_query($connect, "SELECT * FROM users WHERE username='$user';", MYSQLI_USE_RESULT);
$row = mysqli_fetch_assoc($query);
?>
<h4>BlogHub > Profile > <?php echo $row['fname']." ".$row['lname']; ?></h4>
<div id="profileAva">
<img src="<?php echo $row['avatar']; ?>" />
</div>
<h5 id="infoDisp" style="margin:3px;"><?php echo "ID #".$row['ID']." - ".$row['fname']." ".$row['lname']." - ".$row['username']." - ".$row['email']." - ".$row['posts']." Posts"; ?></h5>
<?php
$id = $row['ID'];
$recentPost = mysqli_query($connect, "
SELECT *
FROM `blog_posts`
WHERE poster_id='$id'
LIMIT 1
", MYSQLI_USE_RESULT);
$postRow = mysqli_fetch_assoc($recentPost);
?>
<p></p>
<div id="changeAva">
<button class="cancelQuery">x</button>
<center>
<form style="padding-top:20px;" class="boxI" enctype="multipart/form-data" action="changeAva.php" method="POST">
<input style="padding-bottom:15px;" type="file" value="Choose a Avatar" name="file"/><br />
<button type="Submit">Submit</button>
</form>
</center>
</div>
<div id="changeInfoBox">
<button class="cancelQuery">x</button>
<center>
<form action="changeInfo.php" method="POST">
First Name: <input type="text" name="fname" value="<?php echo $row['fname']; ?>" /><br />
Last Name: <input type="text" name="lname" value="<?php echo $row['lname']; ?>" /><br />
Email: <input type="text" name="email" value="<?php echo $row['email']; ?>" /><br />
<button type="submit">Submit</button>
</form>
</center>
</div>
<?php
}
else {
echo "<center><p>You need to be logged in to view this page.</p></center>";
}
include('footer.php');
?>
There is no restriction on number of queries executed during a script execution. There is however no reason that you couldn't get this information in a single query. You would use a JOIN to do this.
This might look like this:
SELECT bp.*
FROM users AS u
INNER JOIN blog_posts AS bp
ON u.id = bp.poster_id
WHERE u.username = '?'
The particular problem you mention in comment to other answer is because you need to call mysql_free_result() before making your next query.
Related
I am new to PHP, and have a web form, that I am using PHP to get data from the database. What I have currently done, as I havent been able to find out another solution to do so (despite my searching - probably dont know the correct terms to look for), is individually executing a SQL Query for each input field on my form.
As below:
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<?php
$asset_tag_sql = "SELECT HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$asset_tag = sqlsrv_query($database_connection, $asset_tag_sql);
?>
<input type="text" id="AssetTag" disabled value="<?php while ($asset_tag_option = sqlsrv_fetch_object($asset_tag)){echo $asset_tag_option->HardwareAssetAssetTag;} ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<?php
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$serial_number = sqlsrv_query($database_connection, $serial_number_sql);
?>
<input type="text" id="SerialNumber" disabled value="<?php while ($serial_number_option = sqlsrv_fetch_object($serial_number)){echo $serial_number_option->HardwareAssetSerialNumber;} ?>" />
</div>
</div>
Is there anyway to have one PHP piece of code to do one SQL query and then use that to fetch and echo the value for both input fields, as opposed to the two above?
Try it like this?
<?php
$asset_sql = "SELECT HardwareAsset.HardwareAssetAssetTag,HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'"
$asset_result = sqlsrv_query($database_connection, $asset_sql);
$asset_data = sqlsrv_fetch_object($asset_result);
?>
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<input type="text" id="AssetTag" disabled value="<?php echo $asset_data->HardwareAssetAssetTag; ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<input type="text" id="SerialNumber" disabled value="<?php echo $asset_data->HardwareAssetSerialNumber; ?>" />
</div>
</div>
Why not just select two fields from the initial query like this:
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber,
HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE
HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
Im currently coding a website in php, unfortunately ive hit a road block were i cant seem to get my amend.php and update.php pages to work and update on my created display page below is the code.
Display page displays a table with descriptive columns when the hyperlink 'amend' is select it runs the amend.php.
Amend
<?php
include 'connection.php';
$id = $_GET ['theid'];
$query = "SELECT * FROM place WHERE placeid = '$id'";
$results = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($results);
?>
<?php include 'header.php'; ?>
<body>
<h2>Amend</h2>
<form method="post" action="updateplace.php">
<fieldset class="fieldset-width1">
<input type="hidden" name="hiddenID" value= "<?php echo $row['placeid']; ?>" />
<br />
<br />
<label class="align" for="txtplacename">Place Name: </label>
<input type="text" name="txtplacename" value = "<?php echo $row['placename']; ?>" />
<br />
<br />
<label class="align"for="txtplacedesc">Place description: </label>
<input type="text" name="txtplacedesc" value = "<?php echo $row['placedesc']; ?>" />
<br />
<br />
<label class="align"for="txtplacecat">Place category: </label>
<input type="text" name="txtplacecat" value = "<?php echo $row['placecat']; ?>" />
<br />
<br />
<label class="align" for="txtplaceimg">Place image: </label>
<input type="text" name="txtplaceimg" value = "<?php echo $row['placeimg']; ?>" />
<br />
<br />
<input type="submit" value="Submit" name='submit' />
</fieldset>
</form>
</p>
<?php include 'footer.php'; ?>
</body>
</html>
This php page works as it displays all the data from phpmyadmin using the selected id.
update
<?php
include 'connection.php';
if(isset($_POST['submit'])){
$placeid = $_POST['hiddenID'];
$placename = $_POST['txtplacename'];
$placedesc = $_POST['txtplacedesc'];
$placecat = $_POST['txtplacecat'];
$placeimg = $_POST['txtplaceimg'];
}
$query = "UPDATE place
SET placename = '$placename';
SET placedesc = '$placedesc';
SET placecat = '$placecat';
SET placeimg = '$placeimg';
WHERE
placeid = '$placeid'";
mysqli_query($connection,$query);
header("location:admin.php");
when i select the submit button the header redirects me however none of the columns i change will have been updated. Any help would be appreciated thanks
Look at your UPDATE query,
$query = "UPDATE place
SET placename = '$placename'; <==
SET placedesc = '$placedesc'; <==
...
You're terminating your UPDATE operation in every line using ;, which is breaking your query. Furthermore, your UPDATE query itself is wrong, it should be like this:
$query = "UPDATE place SET placename = '$placename', placedesc = '$placedesc', placecat = '$placecat', placeimg = '$placeimg' WHERE placeid = '$placeid'";
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attacks. Also here's a good read on how you can prevent SQL injection in PHP.
You should not just assume the query was successful. Replace your mysqli_query line with this to figure out what is going on:
if (!mysqli_query($connection, $query)) {
echo("Error description: " . mysqli_error($connection));
die();
}
Assuming you have some sort of error, it will prevent the redirect and display. If you still get a redirect, there was nothing wrong with the query itself, rather your $placeid value does not exist in the database.
Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.
So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...
I'm going to make edit menu in my web. so I direct the page from product into edit page. What I'm confused is how to get the productID from product's page to use in edit page?
Here is my code in product
<?php $query= "SELECT * FROM game";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<div class="gameBox">
<div style="margin:5px;">
<?php echo "<image src=\"images/".$data['gameId'].".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <?php echo $data['gameName'];?></div>
<div class="myLabel">Developer</div><div>: <?php echo $data['gameDeveloper']; ?></div>
<div class="myLabel">Price</div><div>: $ <?php echo $data['gamePrice']; ?></div>
<br />
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
<input type="button" value="Delete"/>
</div>
</div>
<?php } ?>
and it's my code in edit page
<?php include("connect.php");
$id[0] = $_REQUEST['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" id="gameName" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" id="gameDeveloper" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" id="gamePrice" name="gamePrice"/></div>
<br/>
<div id="txtError">
<!--error message here-->
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php } ?>
When I try to access edit page, there's an error it said
"Undefined index:$id[0] = $_REQUEST['id'];"
in edit page.
Could anyone help me?
It looks like you're confusing two methods of passing data between pages, forms and query strings in <a href...>s.
Forms:
Data is in <input>-type elements (or friends) and inside a <form...> tag.
For example
<form action="handler.php">
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="submit">
</form>
Usually passed via POST and accessed in PHP via $_POST.
For example, the values in the text boxes referenced above would be accessed with something like:
<?php
echo $_POST['var1']; // First text box
echo $_POST['var2']; // Second text box
Links:
Passed as query strings in <a href...>, for example:
Click Me
Usually passed via GET and accessed in PHP via $_GET.
For example, the values in the query string provided above would be accessed with something like
<?php
echo $_GET['var1']; // "foo"
echo $_GET['var2']; // "bar"
So in this case it looks like you're hyperlinking an input button -- which is not the usual way to do things, but you would fix it by changing this:
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
To, this
<input type="button" value="Edit"/>
And then reference the variable in edit.php as $_GET['id'].
But since you know it's going to be an integer and nothing else, something like:
$id = (int)$_GET['id'];
Is good enough sanitation (at least for that variable).
Lastly, I notice you assign a variable to $id[0] but then reference $id. Assigning a variable to $id[0] is not the same as assigning it to $id, as $id is an array in the former and an integer in the latter. It seems to me that you can just drop the [0] w.r.t. $id in your edit.php
You can pass through the query string
<a href="edit.php?<?php $id=$data['gameId'];?>>
In this case your PHP code will get change to
$id[0] = $_SERVER['QUERY_STRING'];
Add the id as a parameter to your edit url:
<input type="button" value="Edit"/>
also at the top of your edit.php:
$id = $_REQUEST['id'];