PHP & MySQL - query confusion [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a table row with PHP for each value in my MySQL database.
The siteName and siteId are being pulled correctly, and displaying fine how they are.
However, when I try to use a similar type of logic with the query in the if statement, it does not work as well. Currently, it deletes all rows from the folders table in my database, instead of just the one I have clicked on.
Hope that makes sense.
$results = mysqli_query($conn, "SELECT * FROM folders WHERE hidden = 0 ORDER BY siteName asc");
while ($row = mysqli_fetch_assoc($results)) {
<tr>
<td>
<span>
<?php echo($row["siteName"] . ' (' . $row["siteId"] . ')') ?>
</span>
<form method="POST">
<button name="deleteFolder">CLICK</button>
</form>
<?php
$conn = mysqli_connect($server, $username, $password, $database);
if (isset($_POST['deleteFolder']))
{
// deletes everything?
$testing = mysqli_query($conn, "DELETE FROM folders WHERE siteId = '".$row['siteId']."'");
}
?>
</td>
</tr>
<?php } ?>

This code is deleting everything currently because you're executing the delete query inside the loop that's displaying all the folders, using the id of each folder and deleting them as soon as it fetches them.
Pass the site id to delete as the button value, and delete before displaying the table if that value is set.
<?php
$conn = mysqli_connect($server, $username, $password, $database);
// delete first if the button was clicked
if (isset($_POST['deleteFolder']))
{
// use the value from $_POST here
$testing = mysqli_query($conn, "DELETE FROM folders WHERE siteId = '".$_POST['deleteFolder']."'");
}
$results = mysqli_query($conn, "SELECT * FROM folders WHERE hidden = 0 ORDER BY siteName asc");
while ($row = mysqli_fetch_assoc($results)): ?>
<tr>
<td>
<span>
<?php echo($row["siteName"] . ' (' . $row["siteId"] . ')') ?>
</span>
<form method="POST">
<!-- use the site id as the value of this button -->
<button type="submit" name="deleteFolder" value="<?= $row['siteId'] ?>">CLICK</button>
</form>
</td>
</tr>
<?php endwhile; ?>
Also, I didn't address it here but this query is vulnerable to SQL injection. Look into binding the site id value to a prepared statement instead of concatenating the value into your SQL.

First; I'm guessing that you already have a DB conn in order to execute the first query, so you don't need to create a new connection for each row.
Second; When you click the button, it should submit a POST request with the data to a php file that will execute the query (deletion) - like #Don't Panic has suggested. The way your logic is now, you are running the delete check inside the loop when the page loads.

Related

I want to add a value in a database table (particular column only not all column) how can I do it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
table has following column,
id , name, address, phone, city
all information except city is filled with normal php form, now I want to fill column "city" with dropdown option.
<select id="dropdown" name="cityName">
<option value="NewYork">New York</option>
<option value="California">California</option>
<option value="Dallas">Dallas</option>
</select>
This is hard to answer without seeing any other code but here is something generic using PDO and a prepared statement for the PHP side of things. You, of course, need to submit the select field values to your server from the html page either by form action or ajax with JavaScript. I recommend keeping your database config values in it's own file and including it in the separate file that will perform the database update query.
<?php
// It's recommended to keep these config values in their own file but including it here for reference
$servername = "localhost";
$username = "yourdatabaseusername";
$password = "youpassword";
$databasename = "databasename";
// Set up the database connection
$conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set variables for city name from the form and an id of the row you'd like to update
$city = $_POST['cityName'];
$id = 'valueforid';
// If there is a value for city, try to do the DB update
if (isset($city)) {
try {
$stmt = $conn->prepare("UPDATE tablename SET city = :city WHERE id = :id");
$stmt->execute(array(':city' => $city, ':id' => $id));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
}
?>
This is purely an example, you need to tailor this to your unique set-up and server configuration since this is using PDO. Additionally you need to update the table name to the table's name in your database. Lastly, sanitize data etc from the POST before even entering it in the DB.
Hope this gets you on the right track.

mySQL - Can't delete table row with PHP (not showing an error)

I've spent today going through tons of similar questions and trying to figure out what is wrong with my code, lots of issues people had with back ticks, quotes, etc but none seem to help or change my cause. My code is no producing any errors, but when I use echo to print out my query results, it seems that the id is not getting a value.
In my delete.php:
<?
ini_set('display_errors',"1");
$username="xxx";
$password="xxx";
$database="xxx";
$conn = new mysqli(localhost, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = (int)$_GET['number'];
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id."");
$conn->close();
?>
And the delete button in my main.php (the rest of the php is correctly displaying my table with data):
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
Can someone help pick out what is causing my rows not to delete when I hit the delete button that I have created, or maybe something that more clearly can help me debug? (I don't want to use checkboxes for this).
EDIT:
I also tried this code (while defining the function as $sql and I'm getting a "Success" message:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
EDIT 2:
I changed the structure following the advice that I should use POST, thinking I might have caught something I didn't notice before, but still not working.
echo "<td><form method='post' action='delete.php'>
<input type='hidden' name='row_id' value=".$row['id']." />
<input type='submit' name='delete_row' />
</form>";
-
if(isset($_POST['delete_row'])) {
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");
$stmt->bind_param('i', $_REQUEST['row_id']);
$stmt->execute();
}
If I do it the above way, nothing happens. Also tried this way, and get a syntax error:
if(isset($_POST['delete_row'])) {
$id = $_POST['row_id'];
$sql = "DELETE FROM tourdates WHERE id=".$id;
mysqli_query($conn,$sql);
}
A potential problem that I can see, is that you are not quoting localhost so php will look for a constant called localhost:
$conn = new mysqli('localhost', $username, $password, $database);
^ ^ here
You are also not checking for errors so that is why you don't see any. The easiest way to fix that, is to have mysqli throw exceptions. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
I also don't know if you can mix procedural and object oriented mysqli like that. You should probably stick to the OOP version.
Apart from that you should not use a link (GET request) for your delete actions. What if a web-crawler or a browser extension tries to fetch the links? Instead you should use a POST request (like a form with a button).
Edit: There is another problem which causes you not to get your ID and as you cast it to int, you will always get 0:
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
^ Oooops, closing the href attribute value here...
Your id gets placed after the value / outside of the quote of the href value. You can easily verify this if you look at the source of your page.
You need:
<td><a href='delete.php?number=".$row['id']."'>Delete</a></td>
Replace these two parts of code in your php file, first write your host in the quotations
$conn = new mysqli('localhost', $username, $password, $database);
in your where condition you wrote id=".$id."" replace it with id=".$id
write it as:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id);
Edited:
If you want to see error in your query then use the below code:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id) or die(mysqli_error($conn));
why not use try and catch to see your error?
anyways try this
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");<br>
$stmt->bind_param('i', $_REQUEST['number']);<br>
$stmt->execute();
could this be the problem ?
$id = (int)$_GET['number'];
May be this would be better... ?
$id = intval($_GET['number']);
Anyway if, echo($query) print an empty id, this is probably because your parameter is not an integer.

How do i make a list of items that takes data from a MySQL database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an HTML/CSS "contentbox"(It's basically a box that includes an image, title, description, name, etc of a product or item) and i have a database table with all this information for a lot of items/products.
I want to take all this data from product1(title, image, description) from the database and put it in my contentbox.
And i want to do this with all my products from my table and display all this contentboxes below each other. Sort of like the craigslist for sale ads that are in a list.
How do i do this? do i need javascript or where do i start? I don't know much about programming and i'm learning as i go.
I realize i should put some code in my questions so here goes another question:
I have a div container that looks like this:
<div class="contentBox">
<div id="column1">
<img src="images/gallery/girlthinking.jpg" alt="" id="imagen">
</div>
<div id="column2">
<p class="tituloanuncio"><b>Titulo del anuncio</b></p>
<p class="descripcionanuncio">Descripcion kfewoijfew</p>
</div>
<div id="column3">
<p class="precioanuncio"><b>$1000</b></p>
<p class="contactoanuncio"><b>Contacto<br></b>DueƱo: Alejandro<br>Telefono: 8331578460<br>jorgegilcavazos#gmail.com<br>Facebook</p>
</div>
</div>
It works in html, i want to replace the default values a put in there with data from my table, for example where it says.
<div id="column2">
<p class="tituloanuncio"><b>Titulo del anuncio</b></p>
<p class="descripcionanuncio">Descripcion kfewoijfew/p>
</div>
I would like to replace "titulo del anuncio" with the column 'anuncio_titulo' and replace "descripcion kfewoijfew" with the column 'anuncio_descripcion'.
I have this php code that displays all data from the 2 previus columns i mencioned
$result = mysqli_query($con,"SELECT * FROM anuncio");
while($row = mysqli_fetch_array($result)) {
echo $row['anuncio_titulo'];
echo $row['anuncio_descripcion'];
}
How do i echo my initial html div container replacing the default text i put with the new columns?
I hope this makes sense.
You need to first fetch the data from database (read about MySQL, mysqli PHP function). Then you need to pass the data to the site that user sees using PHP (read about PHP). Finally you need to display the data with HTML (read about HTML with PHP).
Nice explanation of mysqli functions is here. To fetch data:
Connect
Create query
Execute query
Get data from query
First connect:
$db = new mysqli('localhost', 'user', 'pass', 'demo');
// check if connection succeeded
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
Then create and execute query:
$sql = "SELECT * FROM `users` WHERE `live` = 1"
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
and get data from query
$usernames = array();
while($row = $result->fetch_assoc()){
$usernames[] = $row['username'] . '<br />';
}
Once you have an array, pass it to your view and print, for example as a part of a table:
<table>
<?php foreach($username in $usernames): ?>
<tr><td><?php $username ?> </td></tr>
<?php endforeach;?>
</table>
If you do not need to change data without reloading the page, you don't need javascript or ajax. I can see several ways you can do what you intend to, but will just explain the easiest one.
First is to assign the text to the variable and print it. If it needs to be changed with data from databse then just assign the value to that variable.
<?php
$title = "Titulo del anucio";
$desc = "Descripcion kfewoijfew";
// it has default values, let's say you want to fill them with data from db now
if(/* some condition here, like data from GET : $_GET['change_data'] == true or something */) {
$db = new mysqli('localhost', 'user', 'pass', 'demo');
// (...) and so on like I wrote above, query the data and assign to value
$res = $result->fetch_assoc() // if you know there is one result you can shorten it
$desc = $res['anuncio_descripcion'];
$title = $res['anuncio_titulo'];
}
?>
<div id="column2">
<p class="tituloanuncio"><b><?php echo $title;?></b></p>
<p class="descripcionanuncio"><?php echo $desc?>/p>
</div>

$result = mysql_query()

I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli

Adding control to a table (PHP) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP / MYSQL Add button to column
Please correct any mistakes throughout this question - I am very new to both PHP and MYSQL.
My goal is to create a table, that I will display onto a web page that looks something like this:
I have done the following. Any help on where I go wrong is much appreciated.
Created a MYSQL Table named "CustomerInformation"
Added five columns to the table, identical to the five columns in the picture above; (id, name, email, is_admin, Action).
I made four $POST text boxes whose data will be passed into each column (other than the last one as I want an "action" button to appear there).
Below I will show my full code for which I used in order to populate a new row in my CustomerInformation table.
<?php
// Connect to the database
mysql_connect ("localhost","username","password") or die ('Error: ' . mysql_error());
echo "connected to database!";
mysql_select_db ("database");
// Create variables to retrieve the POST data
$ID= $_POST['textbox1'];
$C_ID= $_POST['textbox2'];
$Value= $_POST['textbox3'];
$Count= $_POST['textbox4'];
$action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
// Insert data into table
$query = "INSERT INTO CustomerInformation (ID,C_ID,Value,Count,Action)
VALUES(
'".$ID."', '".$C_ID."', '".$Value."', '".$Count."','".$action."')";
mysql_query($query) or die ('Error updating database');
echo "Database updated successfully!";
?>
The only problem occurs when I include the line: $action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
I am clearly butchering this line, and I would greatly appreciate any help at all on this one!
The answer to your question is quite simply mysql_real_escape_string. Apply it on each string variable before you intermingle it with the SQL command.
It's simpler however not to bother with the old mysql_ API. You can keep the query separate from the data and avoid the effort with:
$db = new PDO('mysql:host=hostname;dbname=db', 'username', 'pwd');
$db->prepare(" INSERT INTO CustomerInformation
(ID,C_ID,Value,Count,Action) VALUES (?,?,?,?,?) ")
->execute(array($ID, $C_ID, $Value, $Count, $action));

Categories