I`m trying to parse date in PHP. I copy part of several examples but it is not working.
What I am trying to do is :
I have a PHP file that receives a variable 'parttype' and runs a query.
<?php
$parttype = $_POST['parttype'];
echo "$parttype";
$conn = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($conn , "shop") or die ("db will not open");
$query = "SELECT * from parts where parttype='$parttype'";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo '<table border="1" align ="center"><tr><th>Id</th><th>Name</th><th>Price</th><th>InStock</th><th>Description</th><th>SUpplier</th><th>Quantity</th><th>Remove</th></tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr><form action='ppcomppartout.php' method='post'><td><input type='hidden' name='partid' value='$row[0]'>" . $row[0] . "</td><td>" . $row[1] . "</td><td>" . $row[2] . "</td><td>" . $row[3] . "</td><td>" . $row[5] . "</td><td>" . $row[6] . "</td>
<td><input type='text' name='qtty' placeholder='0'></td><td>Buy <input type='submit'></td>
</form></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
Then in the index.php I have a function get() that posts the variable to data.php
and another function that is not working - function parse(data). I eventually insert a button to get some results, but I wanted the results to come up as soon as I change the values on the select box.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
function get() {
$.post("data.php", {parttype: form.parttype.value },
function(output) {
$("#output").html(output).show();
});
}
function parse(data){
$('#output').append('<select>');
$("select").on("change", function(evt)
{
line_record( $("select option:selected").index(),data)
});
}
</script>
</head>
<body>
<form name="form">
<select name="parttype" style="width: 117px">
<?php
$con = mysqli_connect("127.0.0.1", "root", "") or die ("No connection");
mysqli_select_db($con , "shop") or die ("db will not open");
$query = "SELECT distinct parttype from parts";
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result)) {
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . " </option>";
}
echo "</select>";
mysqli_close($con);
?>
</select>
<!--<input type="submit" value="OK!!"/>-->
</form>
<!--<input type="text" name="parttype">-->
<!--<input type="button" value="Get" onClick="get();" >-->
<input type="submit" value="Get" onClick="get();" >
</form>
<div id="output"></div>
</body>
</html>
Can some one help with this?? What I am doing wrong ??
You don't specify what the problem is exactly, but you should take it step by step.
The first problem you will encounter is probably when you call your get() function on page load. The data you are sending to your php script is:
{parttype: form.parttype.value }
where form.parttype.value seems to be undefined. If you want to send the values of your form, you can change that to:
$("form").serialize()
You should also check your html source as there seem to be multiple closing form tags.
Note: You are dumping your $_POST variable in your sql query without any validation or escaping. You should really switch to prepared statements as your code is vulnerable to sql injection.
Related
I am trying to learn "searching elements from mysql database using php".
For this I created a database named randomdata. In randomdata database there is a table named randomtable. In this table there are four columns: Name, Surname, Email and Gender.
I want to search people by there Gender. For this I tried following query.
$query="SELECT * FROM randomtable WHERE Gender =' ".$gender . " ' ";
I tried both, GET and POST functions. But still I am not able to take output. I am using these.
Windows 8
Wampserver
Notepad++
I restarted server and PC, but nothing changed. Below is my complete code.
Find Entries:
Male
Female
<?php
if(isset($_POST['submit']))
{
echo $gender=$_POST['$gender'];
$connect=mysql_connect("127.0.0.1","root","", "randomdata");
if($connect)
{
//echo 'I am connected';
$query="SELECT * FROM randomtable WHERE Gender =' ".$gender . " ' ";
echo $query;
$results=mysqli_query( $connect,$query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>
It looks like the issue is with assigning the POST variable to $gender
Currently you are using
echo $gender=$_POST['$gender'];
Please try changing this to
$gender=$_POST['gender'];
UPDATE
After testing your code it seems the isset is the issue. There is never a POST['Submit'].
To fix this you need the name attribute in the submit input ie
<input type="submit" Value="Search" name="Submit"/>
Also in the query you have spaces either side of the $gender variable. I now have the code working, try with this.
<html>
<body>
Find Entries: <br>
<form action="" method="POST">
<input type="radio" name="gender" Value="Male"> Male </input>
<br>
<input type="radio" name="gender" Value="Female"> Female </input>
<br>
<input type="submit" Value="Search"/>
</form>
<?php
if(isset($_POST['gender']))
{
//print_r($_POST);
$gender=$_POST['gender'];
$connect=mysqli_connect("127.0.0.1","root","password", "randomdata");
if($connect)
{
//echo 'I am connected';
$query="SELECT * FROM randomtable WHERE Gender = '".$gender . "' ";
//echo $query;
$results=mysqli_query( $connect,$query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>
mysql_connect should be mysqli_connect
Try this...
$query="SELECT * FROM randomtable WHERE Gender ='".$gender . "'";
Removed extra spaces in query
Is there no output at all? Very odd indeed.
What are you posting?
Are you sure that you're including 'submit' in your test post?
If this doesn't help, perhaps there's a more severe error that's not allowing the script to run? Are you able to see the php or apache error logs?
I guess you were intending to assign the "submit" index to the $gender variable instead of the "gender" index?
Try the code below:
<?php
if(isset($_POST['submit']))
{
$gender = $_POST['submit'];
$connect = mysql_connect("127.0.0.1", "root", "", "randomdata");
if($connect)
{
$query = 'SELECT * FROM randomtable WHERE Gender = "' .$gender .'"';
$results = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($results))
{
echo $row['Name'] . "<br/>" . $row['Surname'] . "<br/>" . $row['Email'] . "<br/>" ;
}
}
else
{
die(mysql_error());
}
}
?>
I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.
This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];
Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.
I have a very simple chat system I've built using PHP and MySQL (this is my second day ever using these languages) and I am wondering if there is any way to auto refresh the table data I'm pulling from my database and loading into an html table via PHP without having something like Javascript go and reload the whole web page... just reloading the html table with the data in it that PHP filled it up with.... Does that make sense?
Here is my code if it helps (for /chat.php)
<html><head></head><body><center>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" name="submitButton"/> <button name="Refresh Chat">Refresh Chat</button>
</form>
<div style="width:100%;">
<?php
$host="****";
$user="****";
$password="****";
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db("defaultdb", $cxn);
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
$ipaddress = getenv(REMOTE_ADDR);
}
$message = nl2br(strip_tags(nl2br($_POST["message"])));
if (isset($_POST['submitButton'])) {
if ($message != "") {
mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");
}
header('Location: chat.php');
}
$message = "";
$data = mysql_query("SELECT * FROM ChatTest ORDER BY TimeStamp DESC") or die(mysql_error());
Print "<table border cellpadding=3 width='100%' style='table-layout:fixed'>
";
Print "<tr>";
Print "<th style='width:10%;'>ID:</th><th style='width:10%;'>TimeStamp:</th><th style='width:70%;'>Message:</th>";
while($info = mysql_fetch_array( $data )) {
Print "
<tr>";
Print " <td>".$info['ID'] . "</td> ";
Print " <td>".$info['TimeStamp'] . " </td>";
Print " <td style='white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word'>".$info['Message'] . "</td></tr>
";
}
Print "</table>";
mysql_close($cxn);
?>
</div></center></body></html>
The technique is called AJAX and one of the easiest libraries to add to the project would be jQuery. I assume your issue isn't with JavaScript, but with the idea of reloading the entire page.
UPDATE
Because I'm such a nice guy ;) This should work, more or less, I haven't tried it out, so there might be a typo or two:
<?php
$host="****";
$user="****";
$password="****";
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db("defaultdb", $cxn);
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
$ipaddress = getenv(REMOTE_ADDR);
}
$message = nl2br(strip_tags(nl2br($_POST["message"])));
if (isset($_POST['submitButton'])) {
if ($message != "") {
mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");
}
header('Location: chat.php');
}
$message = "";
$data = mysql_query("SELECT * FROM ChatTest ORDER BY TimeStamp DESC") or die(mysql_error());
$tbl = '';
$tbl .= "<table border cellpadding=3 width='100%' style='table-layout:fixed'>
";
$tbl .= "<tr>";
$tbl .= "<th style='width:10%;'>ID:</th><th style='width:10%;'>TimeStamp:</th><th style='width:70%;'>Message:</th>";
while($info = mysql_fetch_array( $data )) {
$tbl .= "
<tr>";
$tbl .= " <td>".$info['ID'] . "</td> ";
$tbl .= " <td>".$info['TimeStamp'] . " </td>";
$tbl .= " <td style='white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word'>".$info['Message'] . "</td></tr>
";
}
$tbl .= "</table>";
mysql_close($cxn);
if (isset ($_GET['update']))
{
echo $tbl;
die ();
}
?>
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
</head><body><center>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" name="submitButton"/> <button name="Refresh Chat">Refresh Chat</button>
</form>
<div id="messages" style="width:100%;">
<?php echo $tbl; ?>
</div></center>
<script type="text/javascript">
$(document).ready (function () {
var updater = setTimeout (function () {
$('div#messages').load ('chat.php', 'update=true');
}, 1000);
});
</script>
</body></html>
As for coding techniques, you might want to look into SQL-injections and maybe writing cleaner HTML, but I'm sure you'll get there :)
the only way you would do it without javascript is to use an iframe for the chat interface, and a meta refresh.
but why not use javascript?