Update whole table in one query - php

If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:
<form action='update.php' method='post'>
<table border='1'>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exchange";
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($conn,"utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
echo "</tr>";
}
}
$conn->close();
?>
<table>
There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...

I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:
if ($result->num_rows > 0) {
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "</tr>";
}
}
On the php side to process the input, you can do something like this:
$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
//do insert with $id
}

Related

Printing text to textbox and input from sql database in php

I would like to ask if someone could help me with this problem.
I want to prefill the input and textbox from the SQL database. I have tried it many times and I didn't succeded.
This is the code:
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['id'].">".$row['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
?>
Thank you in advance.
Ahhh! You have a While Loop INSIDE a While Loop!!
And both are processing mysqli_fetch_array($result) and therefore the inner loop destroys the $result used in the outer loop.
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
// changed code here
// 1 you dont need to connect twice
//$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
// use different var here
// and then use it in the related function calls
$result1 = mysqli_query($conn, $query);
if ($result1) {
// and of course use a different var to hold the row data
// so you dont overwrite that also
while ($row1 = mysqli_fetch_array($result1)) {
echo "<option value=".$row1['id'].">".$row1['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
Seperate issue, you dont appear to have a <form> and </form> tag in this code. Without that the data placed in input fields will never be transmitted as a form to the PHP script for processing
BIG NOTE
Your script is open to SQL Injection Attack.
Even if you are escaping inputs, its not safe!
You should consider using prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenated values
So to prepare the relevant dangerous query
$query = 'SELECT nazev, popis FROM recepty WHERE id = ?';
$stmt = $conn->prepare($conn, $query);
$stmt->bind_param('i', $_POST['id_recept']);
$stmt->execute();
$result = $stmt->get_result();
. . .

how to php echo individual column values of a result row from mysql query?

The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " .
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}

inserting into SQL with PHP

Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>

How to put my data from a table using PHP/MySQL

I know this question has been asked multiple times but looking through and trying the solutions has not got me far.
I would like the table to have a format of:
First name | Last Name
Mike Hannover
Steve Dortmund
however I am not sure how to achieve this, it currently lays out like as I have taken the table coding out that I have tried.
FirstName: Mike - LastName: Hannover
FirstName: Steven - LastName: Dortmund
I have attached my PHP code below and thanks in advance for your time and help.
<body>
<h1>Clients information</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "lastgo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FirstName, LastName FROM info";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "FirstName: " . $row["FirstName"]. "
- LastName: " . $row["LastName"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Probably the easier way is to build your table is to do it as a table.
// Just looking at this part of the code.
if ($result->num_rows > 0) {
// Begin a table
echo "<table>";
// Create a header row
echo "<tr><th>First Name</th><th>Last Name</th></tr>";
while($row = $result->fetch_assoc()) {
// output data for each row
echo "<tr><td>" . $row["FirstName"]. "</td><td>" .
$row["LastName"]. "</td></tr>";
}
// Close table
echo "</table>";
}
As far I understand you want to print your FirstnName and LastName like so
Change your while loop to:
echo "<table>";
echo "<th>FirstName: </th><th>LastName</th>";
while($row = $result->fetch_assoc()) {
echo "<tr>".
"<td>" .$row["FirstName"] ."</td>"
."<td>" . $row["LastName"]."</td>
.</tr>>";
}
echo "</table>";
you can use a table, then style it the way you want the records to appear
<table>
<tr>
<td>Name</td>
<td>Last Name</td>
</tr>
<?php foreach ($names as $value) : ?>
<tr><td><?php echo $value['Name']; ?></td><td><?php echo $value['LastName']; ?></td></tr>
<?php endforeach; ?>
</table>

Why do I get an undefined variable error when trying to use PHP in two sections of a page?

I am trying to use PHP in two different parts of a page. But when I try to load the page I receive the error: undefined variable $conn. Why am I getting this error?
<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\"
class=\"amount-type\"
placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
You use $conn at the top of your script
$result = mysqli_query($conn, $sql);
Yet you define it further down
$conn = mysqli_connect($servername, $username, $password, $dbname);
You'll need to move that section up to the first before you can run any queries.
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<tbody>
<?php
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\" class=\"amount-type\" placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
You're defining and connecting to the database after you try to use it. Move the connection part above the query. If this is the only place that you will be using the connection the page then this is fine. But if other pages or sections of the page will use the connection you should look at placing this in a common file that is included at the top of every page that uses it.
<tbody>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pizza";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, name, price FROM periperichicken";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>£" . $row["price"] . "</td>";
echo "<td><input type=\"text\" name=\"amount\" class=\"amount-type\" placeholder=\"Amount\"/></td>";
echo "<td>Add to cart</td>";
echo "</tr>";
}
}
mysqli_close($conn);
?>
</tbody>
I'd be pretty sure that you need to define $conn before you call it in the top part of the php code.
PHP is loaded and executed sequentially... You are defining $conn after using it. Try doing it before. I.e.: Move the second blob of PHP above the first one.
For more on PHP execution order, check out this question.

Categories