Data is not enter in database using php [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 7 years ago.
Improve this question
I want to insert data into the database.but when i click on save button than data did not go in database.i did not understand where i did mistake. This is my php code:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "crud";
$conn = new mysqli($host, $user, $password);
mysql_select_db($database);
if(isset($_POST['btn-save']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city_name = $_POST['city_name'];
$sql_query ="INSERT INTO users(first_name,last_name,user_city) VALUES('$first_name','$last_name','$city_name')";
mysql_query($sql_query);
}
?>

You are mixing mysqli and mysql methods ~ ignore the now deprecated mysql_* suite of functions and concentrate on mysqli - learn about prepared statements if you wish to prevent sql injection.
Hopefully the following should insert data.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "crud";
$conn = new mysqli( $host, $user, $password, $database );
if( isset( $_POST['btn-save'] ) ){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city_name = $_POST['city_name'];
$sql ="INSERT INTO `users` (`first_name`,`last_name`,`user_city`) VALUES ( '{$first_name}', '{$last_name}', '{$city_name}' )";
$res=$conn->query( $sql );
if( $res ){
/* all good */
}
$conn->close();
}
?>
I mentioned prepared statements - the following could be used ( hopefully without issue ) in place of the $conn->query() above! The basic idea is that you use a placeholder in the sql statement and then bind variables to those placeholders - believe it or not this method will drastically reduce any chance of sql injection ;/
$sql = "INSERT INTO `users` (`first_name`,`last_name`,`user_city`) VALUES ( ?, ?, ? )";
$stmt = $conn->prepare( $sql );
$stmt->bind_param('sss',$first_name,$last_name,$city_name);
$res=$stmt->execute();
if( $res ){
/* all good ~ display a message or set a var etc */
$stmt->close();
}
$conn->close();

Related

How do I get the value of the form into a MySQL table? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
All I want is to get the var1 from the input into my SQL table. It always creates a new ID, so this is working, but it leaves an empty field in row Email. I never worked with SQL before and couldn't find something similar here. I thought the problem could also be in the settings of the table, but couldn't find anything wrong there.
<input name="var1" id="contact-email2" class="contact-input abo-email" type="text" placeholder="Email *" required="required"/>
<form class="newsletter-form" action="newsletter.php" method="POST">
<button class="contact-submit" id="abo-button" type="submit" value="Abonnieren">Absenden
</button>
</form>
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
// Connection to DBase
$con = new mysqli($host, $user, $password, $dbase) or die("Can't connect");
$var1 = $_POST['var1'];
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
$result = mysqli_query($con, $sql) or die("Not working");
echo 'You are in!' . '<br>';
mysqli_close($con);
is the id a unique id? that's auto-incremented??
if so you should do something like this
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host,$user,$password,$dbase);
$email = $_POST['var1'];
// you might want to make sure the string is safe this is escaping any special characters
$statment = $mysqli->prepare("INSERT INTO table (Email) VALUES (?)");
$statment->bind_param("s", $email);
if(isset($_POST['var1'])) {
$statment->execute();
}
$mysqli->close();
$statment->close();
Simple answer
There are a few things wrong here; but the simple answer is that:
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
...should be:
$sql = "INSERT INTO {$table} (id, Email) VALUES ('?', '{$var1}')";
...OR assuming id is set to auto-increment etc. etc.
$sql = "INSERT INTO {$table} (Email) VALUES ('{$var1}')";
More involved answer
You should really take the time to use prepared statements with SQL that has user inputs. At the very least you should escape the strings yourself before using them in a query.
mysqli
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host, $user, $password, $dbase); // Make connection to DB
if($mysqli->connect_error) {
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("s", $email); // Bind $email {s = data type string} to the ? in the SQL
$query->execute(); // Execute the query
PDO
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
try {
$pdo = new pdo( "mysql:host={$host};dbname={$dbase}", $user, $password); // Make connection to DB
}
catch(PDOexception $e){
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$email]); // Execute the query binding `(array)0=>$email` to place holder in SQL

How do I display the result of this SQL 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 5 years ago.
Improve this question
I can't figure out how to display the result of this query in PHP/MySql. I would like to use a prepared statement if possible.
SELECT count( DISTINCT(video_view_ip) ) FROM video_views
to fetch data from sql and print it using php please use this way
first connect to databse
$con = mysqli_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con,"db_name");
and after connects, retrieve data from table
$sql_fetch_vide_count = "SELECT count( DISTINCT(video_view_ip) ) as video_count FROM video_views ";
$video_result = $con->query($sql_fetch_vide_count);
if (!$video_result) {
die('Could not enter data: ' . mysql_error());
}
//getting the date to array
$row_video = $video_result->fetch_assoc();
//Fetch the count result
$video_count = isset($row_video ['video_count ']) ? $row_video ['video_count '] : 0;
if you fetching all the data from database then use
$array_videos = array();
while ($row_video = $video_result->fetch_assoc()) {
$array_videos [] = $row_video ;
}
you can get all the data into the $array_videos as an array
First, we will need to acquire a connection to the database. For this, we will be using PDO:
<?php
$config = [
'driver' => 'mysql',
'host' => 'localhost', // replace this with the actual mysql host if needed
'port' => 3306, // default mysql port is 3306
'database' => 'my_database', // replace this with the database you are using
'username' => 'admin', // replace this with your username
'password' => 'password', // replace this with your password
];
$connection = new PDO(
vsprintf('%s:Server=%s,%s;Database=%s', [
$config['driver'],
$config['host'],
$config['port'],
$config['database'],
]),
$config['username'],
$config['password']
);
To keep the configuration private, you may store this in a separate file that is read-only. You may then read this configuration with parse_ini_file.
To run the query, and store the results we will have to do the following:
// in this case, we can use fetchColumn to retrieve the count, since it is a single value. However, we will usually want to use fetch() for most cases.
$count = $connection
->query('SELECT count( DISTINCT(video_view_ip) ) FROM video_views')
->fetchColumn();
To display the results, we can simply echo them out:
echo $count;
Check this for example on how to produce your output on php page
EDITED: Added prepared statement prior to OP request
<?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);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>

PHP SQL - Inserting into a table [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 7 years ago.
Improve this question
I have a problem dear stackoverflowers, could someone please help me out?
This is my code:
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "hotelcalifornia";
$room_Number = ($_POST['Room_Number']);
$room_Category = ($_POST['Room_Category']);
$room_Description = ($_POST['Room_Description']);
$room_Detail = ($_POST['Room_Detail']);
$conn = mysql_connect($host, $user, $pass);
$db = mysql_select_db($db, $conn);
mysql_select_db($db, $conn);
$sql = "INSERT TO room (roomNumber, roomCategory, roomDescription,roomDetail) VALUES ('$room_Number','$room_Category', '$room_Description','$room_Detail')";
mysql_query($sql, $conn);
?>
Can someone tell me why i can't insert this data into my table in the database?
It's not INSERT TO, it's INSERT INTO.Thus you shouldn't use mysql functions, instead use mysqli functions as your code is vulnerable to SQL injection.
$host = "localhost";
$user = "root";
$pass = "password";
$db = "hotelcalifornia";
$conn = new mysqli($host, $user, $pass, $db);
$room_Number = $_POST['Room_Number'];
$room_Category = $_POST['Room_Category'];
$room_Description = $_POST['Room_Description'];
$room_Detail = $_POST['Room_Detail'];
$sql = "INSERT INTO room (roomNumber, roomCategory, roomDescription,roomDetail) VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iiss', $room_Number, $room_Category, $room_Description, $room_Detail);
if ($stmt->execute()) {
if($stmt->affected_rows > 0){
echo "New record created successfully";
}
} else {
echo "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
Within the line $stmt->bind_param('iiss', $room_Number, $room_Category, $room_Description, $room_Detail); i corresponds to the integer where s corresponds to string by the order of the variables, which I assume $room_Number and $room_Category are integer values where $room_Description and $room_Detail are string values.

How do I update the values in the table using PHP [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 7 years ago.
Improve this question
How do i actually update the values of table using PHP ? This code is not showing any error and its not updating either.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
if($conn->query(update) === TRUE) {
echo ("Data updated successfully");
}
else
{
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
?>
Hope this one help you!
$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";
Check this part of your code:
if($conn->query(update) === TRUE) {
where it should be:
if($conn->query($update) === TRUE) {
Make sure that you are using the correct credentials (host, username, password, database name) according to your MySQL database.
Also your table name and column name should be correct which are being used in your query.
Make sure that there is a match with your condition part of your query (... WHERE Id='$id'). Check it by running a query in your PhpMyAdmin page, or Search the ID, which is also the one you try to input in your form.
Make sure that the name of the passed variables ($_POST[]) are correct.
Be case sensitive.
Try changing your connection into:
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Other way to execute your query is to simply:
mysqli_query($conn,$update);
Recommendation:
You should escape the values of your variables before using them into your query by using mysqli_real_escape_string() function:
$name = mysqli_real_escape_string($conn,$_POST["Name"]);
Or better, so you won't need to worry about binding variables into your query and as well prevent SQL injections, you should move to mysqli_* prepared statement:
if($stmt = $conn->prepare("UPDATE info SET Name=?, Department=? WHERE Id=?")){
$stmt->bind_param("ssi",$_POST['Name'],$_POST['Department'],$_POST['Id']);
$stmt->execute();
$stmt->close();
}
$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";
mysql_query($update);
$update = "update info set Name='".$name."',set Department='".$dept."' where Id='".$id."'";
if this is not help please provide form code.
Try this
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn)
{
die("ERROR CONNECTING TO DATABASE!");
}
echo "Connected Successfully";
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
$qry = mysqli_query($conn,$update);
if(!$qry) {
echo "Error Updating Details".mysqli_error($conn);
}
else
{
echo "Data updated successfully";
}
mysqli_close($conn);
?>
(Optional) Use secure things. Change to this for more secure.
$id = mysqli_real_escape_string($conn,$_POST['Id']);
$name = mysqli_real_escape_string($conn,$_POST['Name']);
$dept = mysqli_real_escape_string($conn,$_POST['Department']);

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories