I have a script that creates a series of inputs and buttons, retreiving them from a database like this:
while ($row = mysql_fetch_array($sql)){
echo "<input value='".$row['val']."'/><button type='submit'>delete</button>";
}
This script can retreive any number of rows from the database. And the delete button is supposed to delete the input right next to it like this:
$sql="DELETE FROM $tbl WHERE ......";
$delete= mysql_query($sql5, $dbh) or die ("there was a problem");
My question is... is there a way to relate each button with the input next to it?
Thanks in advance!
Utilizing your code as a starting point, make some changes like so:
while ($row = mysql_fetch_array($sql)){
echo "<input value='".$row['val']."'/><button name='delete[" . $row['id'] . "]' type='submit'>delete</button>";
}
Then, where the form gets posted to, in your php:
// Check if the delete button was posted and get the value
$delete = (isset($_POST['delete'])) ? $_POST['delete'] : NULL;
// $delete should contain an array of ids. Iterate over them
foreach((array)$delete AS $id=>$x) {
// NOTE: DO NOT use mysql_ - used here ONLY because your question contains mysql_
$sql="DELETE FROM [table] WHERE id = " . (int)$id;
// Delete the record where the id matches
// Also - on your die, let's SEE the problem, by echoing mysql_error()
$results = mysql_query($sql, $dbh) or die ("there was a problem<br>" . mysql_error());
if ($results) {
// .. code to run if query executed successfully...
}
}
Do not use mysql_
I can't leave an answer without telling you it is insecure and a bad idea to use the mysql_ database extension. It's deprecated in php 5.5.
See Choosing a database API for help with choosing / switching to mysqli or PDO
You shouldn't use button and input together this way.
You can achieve it this way:
while ($row = mysql_fetch_array($sql)){
echo '<input type="submit" name="'.$row['val'].'" value="delete" />";
}
Or you can create many forms - one for each record and set input type as hidden.
Related
I want to take the value of a single MySQL cell and use it as a string inside PHP code - I already know the cell exists, where it is, and nothing else is needed. What's the easiest way to do this? All the examples I've found focus on using a loop to output multiple rows into a table, which seems needlessly complicated for my purposes.
Basically what I want to do is this:
require_once 'login.php'; // Connects to MySQL
$sql = "SELECT name FROM users WHERE id='1'"; // id is determined elsewhere
$result = mysqli_query($connect, $sql);
echo "Your name is " . $result;
But I get an error message that it's not a valid string.
You forgot to fetch record from $result using mysqli_fetch_assoc().
So you can fix your code this way:
$result = mysqli_query($connect, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "Your name is " . $row['name'];
}
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
Here is my code
<?php require_once 'connect.php';
$sql = "SELECT * FROM `db-pages`";
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
}
?>
I've added a couple more rows to the Database and it's returning them all, apart from id=1 in the DB. Any idea why?
try it like this:
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
Double check the title and ensure it's got nothing that will affect php out-putting it.
Also escape all of your DB output using htmlentities, it makes for good practise in the event someone gets creative.
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...
Being quite new with PHP, I cannot find any solution why this does not work. The query is OK and the resource is returned. But I dunno why fetch_assoc does not print values. Thanks
$query=sprintf("SELECT ID,NAME FROM USERS WHERE PASS='%s' AND NAME='%s'",mysql_real_escape_string($p),mysql_real_escape_string($n));
$result=mysql_query($query);
if ($result)
{
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'];
echo $row['NAME'];
}
}
}
Some simple questions to start with:
Have you done a var_dump($row) to see what it returns?
Are you sure that the name and the password you specify are actually in the database?
Have you encrypted the password in the database (and not in the query)?
Have you a valid database connection ? (I know the answer is yes but a double check won't harm anyone and maybe save some headache)
Edit:
Added a link to the man page for var_dump.
As already suggested use mysql_error() to find what goes wrong. (A simple echo mysql_error(); after $result=mysql_query($query); will suffice)
write down out the query to see if something goes wrong with the escaping.
1.Echo out Your $query to see if it is what You like to be for debugging purposes;
2. Check $row['ID'] AND ['NAME'] if they are really UPPER letters;
3. Use mysql error reporting after if ($result){....} else { echo mysql_errno($link) . ": " . mysql_error($link) . "\n"; } where $link is Your DB handle.
Are you sure that rows were returned? You can use mysql_num_rows($result) to get the count. The only thing I can think of looking at your code is that you're passing in the password in plain text and the version in the DB is MD5 or something.