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"]."'";
Related
When user inputs text in 'ctext' field and press accept, I want to fill the value=" " field with user input, i achieved this but it fills all the value fields of same name in the page, how can i achieve it for different value of different ctext input? Anyone please give me solution with example, Many thanks
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
$i=0;
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here" value="<?php $ctext = false; if(isset($_POST['ctext'])){ $ctext = $_POST['ctext']; } echo $ctext[$i]; ?>"></input>
<input type="hidden" name="id" value="<?php $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
$i++;
endwhile;
endif;
endif;
?>
I hope I understand what you want. You want to access the ctext for each individual $pen when printing the corresponding form.
You just need to name your <input> with a unique name and then access that value when printing. A possible solution is this:
<input type="text" name="ctext[<?php echo $pen['id']; ?>]" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } echo $ctext; ?>"></input>
What does it do?
name="ctext[<?php echo $pen['id']; ?>]" ensures a unique name for each $pen. For a $pen with id 1 this will result in name="ctext[1]".
if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } uses $pen['id'] to look up the corresponding value in $_POST['ctext'].
By the way, when outputting user input you should always escape it, e.g. with htmlspecialchars. This will look like this: echo htmlspecialchars($ctext); That way malicious input like "><script>alert('Hello!')</script> won't execute the javascript.
Update: as requested a solution using session to store data:
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
session_start();
if (isset($_POST['ctext'])) {
$_SESSION['ctext'][$_POST['id']] = $_POST['ctext'];
}
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_SESSION['ctext'][$pen['id']])){ $ctext = $_SESSION['ctext'][$pen['id']]; } echo htmlspecialchars($ctext); ?>"></input>
<input type="hidden" name="id" value="<?php echo $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
endwhile;
endif;
endif;
Note: I removed the now unnecessary counter $i. The session handling is mainly done before the while loop (start a session and store POST data). During output the values from the session are used. The name of the input is not an array anymore.
Change name of an input to an array.like this . When you submit the form you will get these values as an array. Give it a try
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here"></input>
I guess your code is misleading you, your form is in while loop so once any of the ctext input is filled your variable $_POST['ctext'] is set on server side and according to your code it sets all the value of ctext once accept is pressed.
You can have different names as a solution or an array indexing in input field name=“ctext[]” to avoid this.
I am retrieving data from SQL using PHP on a page and showing many records at a time using below code.
<?php
//Database Connection File
require_once("config.php");
//Everything Is Okay So Let's Garb This User Contacts Data
$garb = mysqli_query($connection, "SELECT * FROM contacts WHERE A_Id = '$A_Id'");
if(!$garb){
$error = "<div class='error'>There's Little Problem: ".mysql_error()."</div>";
} else {
//Data Is Collected
//Showing The User Data
$idNo = 0;
while($row = mysqli_fetch_array($garb)) {
$C_FullName = $row['C_FullName'];
$C_Gender = $row['C_Gender'];
$C_ContactPhone = $row['C_ContactPhone'];
$C_ContactCell = $row['C_ContactCell'];
$C_Email = $row['C_Email'];
$C_Address = $row['C_Address'];
$C_Group = $row['C_Group'];
$C_Notes = $row['C_Notes'];
echo '
<div class="accordionItem close">
<h3 class="accordionItemHeading">'.$C_FullName.'</h3>
<div class="accordionItemContent">
<div id="contactDetailes">
<form id="updateAllContact'.$idNo.'" method="post" action="">
<p><label>Full Name:* </label><input type="text" name="C_FullName" value="'.$C_FullName.'"></input></p>
<p><label>Gender:* </label><input type="text" name="C_Gender" value="'.$C_Gender.'"></input></p>
<p><label>Contact No(Phone): </label><input type="text" name="C_ContactPhone" value="'.$C_ContactPhone.'"></input></p>
<p><label>Contact No(Cell): </label><input type="text" name="C_ContactCell" value="'.$C_ContactCell.'"></input></p>
<p><label>Email Address:* </label><input type="text" name="C_Email" value="'.$C_Email.'"></input></p>
<p><label>Address: </label><input type="text" name="C_Address" value="'.$C_Address.'"></input></p>
<p><label>Group: </label><input type="text" name="C_Group" value="'.$C_Group.'"></input></p>
<p><label>Notes: </label><textarea type="text" name="C_Notes">'.$C_Notes.'</textarea></p>
<span>
<a class="updateButton">Update</a>
<a class="deleteButton">Delete</a>
</span>
</form>
</div>
</div>
</div>
';
$idNo++;
}
}
?>
Now the problem is that I want to add Update and Delete function for every row retrieved from database. What I want is something like HTML5 Web SQL Databases And Usage or something like HTML5 Address Book using PHP and SQL. So how can I add functions of Update and Delete in my every row data...???
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 2 years ago.
I have encountered an issue with updated my MySQL data which includes HTML data, I continuously fixed errors; however, once one error is fixed it gives another. The current error is as follows:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='Live updates to certain games will also be posted on this website througho' at line 1
I have been scavenging on Stack Overflow for nearly 3 days without any definitive answers. So I am hoping someone can find this!
Here is my PHP form code:
if (isset($_POST['submit'])) {
$WName = mysql_prep($_POST['wname']);
$SName = mysql_prep($_POST['sname']);
$Desc = mysql_prep($_POST['desc']);
$LogoURL = mysql_prep($_POST['logourl']);
$aboutPage = mysql_prep($_POST['aboutpage']);
$query = "UPDATE settings SET name='$WName',subName='$SName',desc='$Desc',logoUrl='$LogoURL',about='$aboutPage'";
// $query = mysql_prep($query);
mysql_query($query) or die(mysql_error());
header("Location: settings.php?=success");
}
The function mysql_prep() can be found on the internet, namely here: https://gist.github.com/ZachMoreno/1504031
Here is the HTML form:
<form role="form" action="" method="post">
<!-- text input -->
<div class="form-group">
<label>Website Name</label>
<input type="text" name="wname" class="form-control" placeholder="
<?php echo $row['name']; ?>" value="
<?php echo $row['name']; ?>" />
</div>
<div class="form-group">
<label>Sub Name</label>
<input type="text" name="sname" class="form-control" placeholder="
<?php echo $row['subName']; ?>" value="
<?php echo $row['subName']; ?>" />
</div>
<div class="form-group">
<label>Description</label>
<textarea name="desc" class="form-control" rows="3" placeholder="
<?php echo $row['desc']; ?>" >
<?php echo $row['desc']; ?>
</textarea>
</div>
<div class="form-group">
<label>Logo URL</label>
<input type="text" name="logourl" class="form-control" placeholder="
<?php echo $row['logoUrl']; ?>" value="
<?php echo $row['logoUrl']; ?>" />
</div>
<div class="form-group">
<label>About Page</label>
<textarea class="form-control" name="aboutpage" rows="6" placeholder="
<?php echo $row['about']; ?>">
<?php echo $row['about']; ?>
</textarea>
</div>
<div class="box-footer">
<input type="submit" name="submit" class="btn btn-primary" value="Submit" style="margin-left:-10px;" />
</div>
</form>
Thanks very much for any assistance that you can provide, I hope this can be figured out and I aim to use this to assist future visitors who encounter the same/similar issues.
Can't believe I didn't see this earlier; the issue I had with MySQL was that the database had the column name 'desc' which I originally had the idea that it meant 'description' but in fact it was conflicting with the keyword 'descending'. This gave the syntax error.
Here is what I found on the MySQL documentation; 9.3 Keywords and Reserved Words
:
Keywords are words that have significance in SQL. Certain keywords, such as SELECT, DELETE, or BIGINT, are reserved and require special treatment for use as identifiers such as table and column names. This may also be true for the names of built-in functions.
On that web link above you can see a list of keywords/reserved words that shouldn't be used or should include back slashes (which I won't go into).
My solution? Don't use reserved words as identifiers!
The easiest solution that you can do is to simply avoid using these words. I prevented using the reserved word 'desc' by changing the identifier to 'description'.
Thanks for all your help! Hope this assists people in the future.
The string returned from your mysql_prep() function has escaped single quotes.
So.. ..you can't use these as delimiters in your query string. Change them to double quotes.
$query = "UPDATE settings SET name = \"$WName\",
subName = \"$SName\",
desc = \"$Desc\",
logoUrl = \"$LogoURL\",
about = \"$aboutPage\" ";
Can you try a $testQuery with just text..
$testQuery = "UPDATE settings SET name = \"ABC\",
subName = \"DEF\",
desc = \"GHI\",
logoUrl = \"JKL\",
about = \"MNO\" ";
Also, you are missing a WHERE clause, or is there only 1 row?
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.
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'];