This question already has answers here:
Resetting array pointer in PDO results
(7 answers)
Closed 3 years ago.
I am trying to create a select box that will display several times on the page, where the options are populated by my SQL query. I am able to get this to display once but when I try to create a second, identical select box, there are no options in the dropdown box. Here is what I have working:
<?php include_once "app/init.php";
$dataQuery = $db->prepare("
SELECT column FROM dataType");
$dataQuery->execute([]);
$dataTypes = $dataQuery->rowCount() ? $dataQuery : [];
?>
<div>
<select>
<?php foreach($dataTypes as $dataType): ?>
<option>
<?php echo $dataType['dataType']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
But when I try to add a second select box, it it blank. I am creating a table that will have this select box on every row for the user to select a data type so I need to recreate this dynamically several times. I am new to php, so what is the best way to go about this?
My init.php to show using PDO:
<?php session_start();
$_SESSION['user']=1;
$db = new PDO ('mysql:dbname=myDB;host=localhost', 'root', 'root');
if(!isset($_SESSION['user'])) {
die('You are not signed in');
};
You can only loop through the PDO statement once, so you should put the result in a temporary array.
Instead of:
$dataTypes = $dataQuery->rowCount() ? $dataQuery : [];
Do
$dataTypes = $dataQuery->fetchAll(\PDO::FETCH_ASSOC);
Related
This question already has answers here:
How to print a MySQL database table in PHP using PDO [closed]
(2 answers)
How can I get an unknown username given an ID?
(2 answers)
Closed 2 years ago.
I have made dynamic links in PHP, to display individual bikes, using the bike ID in my website. This is my code that makes each link individual on my index page:
$bike_id = $bike["bike_id"];
echo '<a href="./item.php?id='.$bike_id.'"><input type="button" value="See More" />';
Now the issue I face is trying to display each bike item pages unique values.
for example, if you selected "Fast bike" on index.php, you'd be taken to a page that had "fast bikes" description and price.
In the database, I have the columns:
"Bike_name",
"Bike_Price",
"Bike_Description
and on each the bikes item page, I want to display these values, but I don't know how to do it.
Here is what I have so far but it's not working:
<?php
require_once(__DIR__.'/includes/db.php'); //connect to the database
$item_id = $_GET['id']; //get the ID of the item
$item_data = mysql_query("SELECT bike_name"); //get the value of the column bike_name
echo "<h2>".$item_data['bike_name']."</h2>"; //display the value of the column bike_name
?>
I was advsed to do this:
// Select item from database
// Store results in $item_data
// echo $item_data[`item_name`];
My connection (I'm not showing my passwords or usernmane)
try {
$Conn = new PDO("mysql:host=".$db_config['db_host'].";dbname=".$db_config['db_name'],$db_config['db_user'],$db_config['db_pass']);
$Conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$Conn->setAttribute(PDO::ATTR_PERSISTENT, true);
$Conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e) {
echo $e->getMessage();
exit();
}
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.
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.
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>
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));