PHP and MySQL using xampp as web server [closed] - php

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 4 years ago.
Improve this question
How can I insert data from a table to another table after the clicking of a button using PHP and MySQL?

Following php script can be used to fetch values from one Table and insert data into another table:
<?php
$servername = "localhost"; //if running on localhost
$username = "root"; // if running on localhost
$password = ""; // empty for mysql default password
$dbname = "database name";
$conn = mysqli_connect($servername, $username, $password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['name of button'])) { // if button is clicked the following code will be executed
$sql_db1 = "SELECT * FROM `table_name_1` WHERE condition"; // if you want to select data based on some constraint.
$sql_db1_query = mysqli_query($conn,$sql_db1); // mysqli_query takes 2 parameters -> connection to database and sql query.
while($row = mysqli_fetch_array($sql_db1_query)){
$sql_db2 = "INSERT INTO `table_name_2`(`column1`,`column2`,`column3`,`column4`) VALUES($row['column1'],$row['column2'],$row['column3'],$row['column4'])"; //'column1' inside $row[] and so on should be replace by the column names of the table in which you want to insert the data
$sql_query_db2 = mysqli_query($conn,$sql_db2);
}
}
?>

I think this takes a little more than a simple answer, try reading a php-mysql tutorial:
https://www.w3schools.com/Php/php_mysql_intro.asp
In plain Mysql you just need a "insert into" statement with a select, as explained here. Then you'll just need to create a php statement to execute this SQL.

Related

Getting blank screen when trying to get data form mysql in json format [closed]

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 10 months ago.
Improve this question
I'm using a php file to get data from mysql database and display that data in json output, while accessing a certain url address like http://example.com/api/users.php
When I use following code I get json response:
<?php
header("Access-Control-Allow-Origin: *");
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
//Connect to MySQL
$mysql = mysqli_connect($servername, $username, $password, $dbname);
$result_array = array();
$sql = "SELECT username FROM users";
$result = $mysql->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
$mysql->close();
?>
But when trying to get multiple cells from "users" row:
$sql = "SELECT username, avatar, email FROM users";
I get a blank screen in my web browser.
What I'm doing wrong?
If the PHP code you posted is returning a valid json when using single field then the basic code is correct. Now when you try to get multiple fields in the query its showing blank screen. This tells me that possibly your SQL $sql = "SELECT username, avatar, email FROM users"; is throwing error. Try to run this sql statement directly on the database, there can be a mistake in column names.
So if the query fails, your $result_array is empty, and hence the json output is blank.

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 dropdown using PHP does not display options from database [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>
Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.
Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.
Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";
Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.

How to edit the value updated in a database from the form using php and mysql [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 7 years ago.
Improve this question
I want to edit the data which is already in the databse.
Suppose I have updated my database, but after an year the user who has updated that database want to edit something like his address which is changed now through the form, then how can we do that. I am posting
<?php
// Create Local variable
$taken = "false";
$database = "railway";
$password = "";
$username = "root";
// Main if statement
//if($userreg && $passreg){
// Connect to database
$con = mysqli_connect('localhost', $username, $password,$database);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
---------
WHAT TO WRITE IN BETWEEN
----------------
mysqli_close($con);
Suppose my table name is Railway and the attributes are time, name, station_to and station_from. I want to change the name.
Please write both the form as well as php and mysql query.
It would be something like this:
$sql = "UPDATE Railway SET name='Joe' WHERE id=5";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

How to connect to MySQL using php [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 been working on a form that uses PHP to send e-mails to my account. To save room and de-clutter my mailbox account I am now trying to now use the same PHP to send the info to a MySQL server to log the data. The code I have been trying to make work keeps giving the same error of:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future
Here is the PHP code that I am currently trying to use:
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'on-boarding';
mysql_connect($host,$username,$password);
mysql_select_db($dbname);
mysql_query("INSERT INTO new_employees ('OnBoardedBy', 'EmployeeName', 'HomePhone') VALUES ('$onboarded_by','$employee_name','$home_phone')");
You should use PDO or MySQLi. I'd recommend directly to use PDO and not MySQLi. PDO has a better integration of Prepared Statements. Do it like this:
try {
$db = new PDO("mysql:host=".$host.";dbname=".$db.";charset=utf8", $user, $password);
} catch(PDOException $e) {
die("Unable to connect. Error: ".$e->getMessage());
}
$link = $db->prepare("INSERT INTO new_employees (`OnBoardedBy`, `EmployeeName`, `HomePhone`) VALUES (?, ?, ?)");
$link->bindvalue(1, $onboarded_by);
$link->bindvalue(2, $employee_name);
$link->bindvalue(3, $home_phone);
$link->execute();
$row = $link->fetch(PDO::FETCH_ASSOC);
edit: Let me add an example for a prepared query.
PHP is not going to support the MySQL extension for much longer anymore. It is recommend to use MySQLi or PDO.
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'on-boarding';
$link = mysqli_connect('$host', '$username', '$password', '$dbname');
mysqli_query($link, "INSERT INTO new_employees (`OnBoardedBy`, `EmployeeName`, `HomePhone`) VALUES ('$onboarded_by','$employee_name','$home_phone')");
Prepared statements are much safer and avoid the risk of sql injection: http://php.net/manual/en/mysqli.prepare.php

Categories