I'm editing some PHP/Javascript codes that control a MySQL Database, and there is an issue where I cannot update old database entries. There are two php files--update.php and success.php.
In the update.php, there is a counter, $c, that is a variable for the rows in order to tell them apart. In success.php, it takes, I presume, the number that $c is (named 'count'), and results into the value for $i. The code is below--
Update.php:
<?php
$c = 0;
while ($row=mysql_fetch_row($result))
{
echo"<tr>";
echo "<td><div class='required'><input type=\"text\" name=\"".$c."ID\" onchange=\"turnWhite(this)\" size=\"7\" value= \"" .$row[3]."\"></div></td>";
echo "<td><select name='".$c."Dataset1' onchange=\"return CheckData(".$c.")\">
<option value='".$row[0]."'>".$row[0]."</option>";
$result1=mysql_query('SELECT Data FROM Database.Table2 ORDER BY Data');
while ($row1=mysql_fetch_row($result1))
{
echo '<option>' . $row[0]. '</option>';
}
echo "</select></td>";
echo "<td><select name='".$c."Dataset2' onchange=\"return CheckData(".$c."\">
<option value='".$row[1]."'>".$row[1]."</option>";
$result=mysql_query('SELECT Data FROM Database.Table2 ORDER BY Data');
while ($row1=mysql_fetch_row($result1))
{
echo '<option>' . $row[0]. '</option>';
}
echo "<td><input type=\"text\" id=\"".$c."Dataset_column2\" name=\"".$c."Dataset_column1\" size=\"30\" value= \"" .$row[2]."\"></td>;
echo "<td><input type=\"text\" name=\"".$c."Dataset_column3\" size=\"30\" value= \"" .$row[3]."\"></td>;
echo "<td><div id='centerbutton'><input type='button' value='Update' onclick='validate(".$c."); return false;' /></div></td>";
$rows = "where 1=1 and `COLUMN2` ='" .$row[2]."' and `COLUMN3` ='".$row[3]."'";
echo "<input type=\"hidden\" name=\"where".$c."\" value=\"".$rows."\">";
$c++;
Success.php:
$previous_URL = $_SERVER['HTTP_REFERER'];
$empty = "";
if(strpos($previous_URL,'update.php') !== false)
{
$i = $_GET['count'];
if ($_FILES[$i."file"]["error"] > 0)
{
}
else
{
}
if (file_exists("C:/Web_content/Upload/" . $_FILES[$i."file"]["name"]))
{
echo "A file of this name already exists.
Please rename your file and upload it again.";
}
if ($stmt = $mysqli->prepare("UPDATE `table` SET `COLUMN2` = ?,
`COLUMN3` = ? ". $_POST['where'.$i] ))
I left some extra code out. My question is, what is it echoing, and how exactly does the $c counter work in update.php. And also in the success.php, what is the $i variable resulting into when it $_GET['count']. I keep getting the error code "A file of this name already exists.
Please rename your file and upload it again" but I'm not even uploading a file (in another column that I left out). Is it a problem in the update or success page? Why isn't up letting me update old database entries in MySQL through these codes?
Also, on a separate issue (but same php codes), sometimes when I try to update my new data, it would give me an error code saying that "A file exists" but under that it'd say "Notice: Undefined index: where170 in C:\Web_content\success.php" on the line where $_POST['where'.$i] is.
And then all my data would turn into NULL (so everything would be gone. But I backed my data up so I simply just import back my data when this happens).
Thank you in advance!
Related
I have a mysql database table called "names" as per below :
All columns (other than id) are stored as varchar
There is a full .php URL stored in Column "Full Name" for each record but I am getting a stackoverflow code error when using the URL in table below.
id
First Name
Surname
Full Name
Profile
1
John
Smith
John Smith
.PHP URL stored as a text string
2
Jane
Doe
Jane Done
.PHP URL stored as a text string
3
Prakash
Singh
Prakash Singh
.PHP URL stored as a text string
I have some mysql and php that returns the records for the first four columns and puts them into a bootstrap table :
<?php
// Include config file
require_once "conn.php";
// Attempt select query execution
$sql = "SELECT * FROM names";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-dark table-hover table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo '<th>First Name</th>';
echo "<th>Surname</th>";
echo '<th>Full Name</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['First Name'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Full Name'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close connection
mysqli_close($link);
?>
What I would like to do:
Make all cell's in Column "Full Name" to be independently clickable.
Onclick, I would like to take the user to the respective profile URL of the record id without opening a new page.
Attempts:
I added a class to the td for Full Name for an onclick event :
echo "<td class='clickme'>" . $row['First Name'] . "</td>";
This made only the first row of the table clickable.
I added some javascript for the class :
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var myVar = window.location.replace("https://www.stackoverflow.com");
};
This partially worked, the page refreshes and redirects to the URL provided. However, as each record has it's own URL (stored in the database) I'd like to retrieve the specific URL rather than input an absolute URL here.
Thanks alot in advance for any help rendered!
I never worked with php but in plane html js. you can pass your url through data attibute.
<td class='clickme' data-url="your_cell_url"> First Name </td>
and then in js file
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var url = this.dataset.url
var myVar = window.location.replace(url);
};
i think it may helps
Try:
echo "<td>" . $row['First Name'] . "</td>";
or if you're using get method for profile page it will look something like this:
echo "<td>" . $row['First Name'] . "</td>";
I have a form on an HTML page which posts a user input to a PHP which executes a SQL statement to get information from a database and output it in JSON. Here is my PHP code to get the JSON data:
<?php
header('Content-type:application/json');
$con = mysqli_connect('localhost','root','','dbname');
if(isset($_POST['submit']))
{
$artist = $_POST['artist'];
$select = mysqli_query($con, "SELECT * FROM tblname WHERE artistName = ". $artist);
$rows = array();
while($row = mysqli_fetch_array($select))
{
$rows[] = $row;
}
echo json_encode($rows);
};
?>
When I submit the form on the HTML page, it goes to the PHP page and I get this result:
[{"0":"6","id":"6","1":"OASIS","artistName":"OASIS","2":"SOME MIGHT SAY","songTitle":"SOME MIGHT SAY","3":"1995-05-06","dateNo1":"1995-05-06"}]
(Code and JSON result have been simplified for this question)
Instead of going to this page, I'd like the data to be displayed nicely on the HTML page so that a user does not see this array. I'm not sure how to do this, any help?
Thank you!
If you want the output formatted nicely, why are you encoding in JSON? JSON, although human-readable, isn't intended to be rendered on-screen as an end product.
I'd recommend looping through the $rows array and building a simple HTML table. You could, of course, wrap the data in any markup you like and even add CSS to style it as you see fit. Here's an example to get you started:
echo "<table>";
foreach($rows as $row) {
foreach($row as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
If you only want some of the data rendered, you can simply echo those values:
foreach($rows as $row) {
{
echo "Artist:" . $row['artistName'];
echo "<br>";
echo "Song Title:" . $row['songTitle'];
echo "<br>";
echo "Date:" . $row['dateNo1'];
}
There are two ways to solve this problem :
Perform AJAX call from Javascript to PHP Page and parse the success response in to the HTML.
Simply echo the values in PHP Page or add HTML itself in PHP Page as suggested by Tim.
I am creating a basic auction site and having a slight issue where when a bid is placed, it sometimes says it's too low, despite it being higher than the current bid. I think this is to do with the way I am getting the current bid, as it's not a very tidy approach in my opinion.
So my HTML/PHP which retrieves and lists the auctions on the page:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
As you can see, I wrap the column/value "CurrentBid" in a div with the ID of the ID in MySQL.
Then when someone places a bid, the following jQuery/AJAX code is called:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
if (bidname == '')
{
alert("No name!")
return false;
}
if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}
$.ajax({
type: "POST",
url: "auction-handler.php",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
}
});
return false;
});
});
As you can see from this code, I assign the variable 'currentbid' by selecting the ID of the div container, and then pulling through the text within it.
I am not sure if this is what is causing me the problem, but it seems likely, I cannot figure out why sometimes it says "Bid too low" despite me putting in a higher price then what is currently in the Current Bid div.
Ideally, I'd like to assign the jQuery variable 'currentbid' with the value directly from MySQL, but I am not too sure if this is possible.
Does anyone know of a way that I can do this? Or is there a better way I can assign a value to the variable?
Thank you
You are comparing strings now instead of numeric values. You should cast your values to floats before comparing.
bid = parseFloat(bid)
currentbid = parseFloat(currentbid);
Also on the server side when processing to bid you should first check the currentBid from the database because it could have changed already.
I have a function to add a new selection using button in the table with ID="maTable"
<button type="button" onclick ="addNew()"> Add More Agent</button>
Using JS :
function Addnew(){
var table=document.getElementById("maTable");
var row=table.insertRow([table.rows.length]-1);
var len=(table.rows.length);
var newid="agentID"+len;
var newida="agentGroup"+len;
var cell1=row.insertCell;
var cell2=row.insertCell;
var cell3=row.insertCell;
var new_optionAgent =
"<select class=\"opsi\"id="'+newida+'">"
+"<option selected=\"selected\"disabled=\"disabled\">Agent<\/option>"
+"<option value=\"agentA\">Agent A<\/option>"
+"<option value=\"agentB\">Agent B<\/option>"
+"<option value=\"agentC\">Agent C<\/option>"
+"<option value=\"agentD\">Agent D<\/option>"
+"<\/select>"
cell1.innerHTML="Choose Agent" +" "+len;
cell2.innerHTML=":";
cell3.innerHTML= new_optionAgent;
}
With this I can get a button that will generate a new selection with 4 options (it works). But now come the problem when I want to change the option with the list from database. Im using php and postgres database. I made the code for the one that isn't generated from the "AddNew" button yet :
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo "<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>";
echo "<option value=\"\" selected=\"selected\"disabled='disabled'>Agent</option>";
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Now I want to make the "AddNew" button that generate a selection with option list from database. I have combined the php code with variable "new_optionAgent" by adding "\" to some symbols. but it doesnt work.
I combine like this
var new_optionAgent =
'<\?php
\$que=pg_query(\"SELECT agentname FROM Agent\")\;
echo \'<select name=\\\"agentname1\\\"class=\\\"opsi\\\" id=\\\"agentGroup1\\\" required>\'\;
echo \'<option value=\\\"\\\" selected=\\\"selected\\\"disabled=\\\'disabled\\\'>Agent</option>\'\;
While(\$row=pg_fetch_array(\$que))
{
echo \'<option value=\"\'\.$row[\'agentname\']\.\'\"> \'\.$row[\'agentname\']\.\'</option>\'\;
}
echo \"<\/select>\"\;
\?>'
this combination is seems very wrong, Any help? Thank you
This is not working because the escaped backslashes is used by PHP for escaping the double quotes. So you will need to add another set of backslases and escape those, or use a single quote string in PHP:
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
echo '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Edit
You can't inline PHP inside a Javascript variable like that. Try this:
<?php
$que=pg_query("SELECT agentname FROM Agent");
$whateverYouWannaCallThisString = '';
$whateverYouWannaCallThisString .= '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
$whateverYouWannaCallThisString .= '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
$whateverYouWannaCallThisString .= '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
$whateverYouWannaCallThisString .= "</select>";
?>
<script type="text/javascript">
var new_optionAgent = "<?php echo $whateverYouWannaCallThisString; ?>";
</script>
More info on escaping
The whole reason you are escaping characters is because you are using characters that surrounds the string itself. E.g: If you are defining a string with double quotes " like this: var myString = "Yolo" and you want to have double quotes " in that string like this: var myString = "Dude, wheres "my" car" then you need to escape the double quotes " thats inside that string like this: var myString = "Dude, wheres \"my\" car".
The same applies to PHP
//Edit :
I edited the variable :
var new_optionAgent =
<?php echo json_encode($whateverYouWannaCallThisString); ?>;
and it works :)
I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D