PHP SQL - Inserting into a table [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 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.

Related

php update record repeat region [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 6 years ago.
Improve this question
As previously stated in my last question on WHAT a cron job is, I'm now trying to write one but seem to get a problem. This is the closest I've gotten. I want to update every record in the database by one more than what it already has.
Example if the field is 30, then when this script is run then it will become 31. But I have MULTIPLE fields and I want all of them to increment by one.
This is what I've currently wrote, but it doesn't work, but I DO get an echo of "Record Updated Successfully" but nothing changes. If I change it so that $Age = $Test and then I plug in a random number for the ID it will end up equaling Test. If I have it say $Age = $NewAge and the random ID, it changes the variable in my database to be 302. I have NO clue where it's pulling that random 302.
Any suggestions?
This is my code below:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "RR";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlSelect = "SELECT id, Age FROM Horse";
$result = $conn->query($sqlSelect);
do{
$id = $row['id'];
$Age = $row['Age'];
$NewAge = $Age + 1;
$Test = 200;
echo $id, ' ', $Age, ' ', $NewAge; ?> <br/>
<?php
$sqlUpdate = "UPDATE Horse SET Age='$NewAge' WHERE id='$id'";
}
while($row = $result->fetch_assoc());
if ($conn->query($sqlUpdate) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
The question is very vague and hard to understand, but as #rjdown said, this will update ALL rows in the database and increment Age by 1.
Note: there is no need for fetching the records from database, nor looping over them. Just one line of SQL will update ALL rows.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "RR";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlUpdate = "UPDATE Horse SET Age = Age + 1";
if ($conn->query($sqlUpdate) === TRUE) {
echo "All records updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

Data is not enter in database 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
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();

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']);

php unable to select data [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'm trying to select a SINGLE value from the mysql database. I have run the query in phpmyadmin and it work great. But when I echo the $result, I get nothing... by the way,for the database and password I use xxx because I don't want to show it... My insert query works very well
Thanks
<?php
//Create Connection
$servername = "localhost";
$username = "root";
$password = "xxx";
$dbname = "xxx";
//Connect
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT StartPriceUnder FROM YJ_Value";
$result = $conn->query($sql);
echo hi;
echo $result;
echo ya;
$conn->close();
?>
Try this:
<?php
$servername = "localhost";
$username = "root";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT StartPriceUnder FROM YJ_Value";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "StartPriceUnder:" . $row["StartPriceUnder"];
}
}
else {
echo "0 results";
}
$conn->close();
?>
You have to fetch your result, so do something like this:
$row = $result->fetch_array(MYSQLI_ASSOC);
After this you can echo it like this:
echo $row["StartPriceUnder"];
For more information about fetch_array() see the manual: http://php.net/manual/en/mysqli-result.fetch-array.php

Is this MySQLi safe? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I wanted to do the follow thing with MySQLi statements or PDO but I experienced a lot of errors on my server.
Please check if the follow example to learn code I did myself will be okay for safety and if it is okay to use it. And hopefully the follow code will help new MySQLi users to learn at least how to start with MySQLi:
<?php
$host = "localhost";
$username = "db_user";
$password = "db_pass";
$dbname = "db_name";
# $db = mysqli_connect($host, $username, $password, $dbname);
if(mysqli_connect_errno())
{
die("Connection could not be established");
}
$username = mysqli_real_escape_string($db, $_GET['user']);
$query = ("SELECT * FROM members WHERE profile='$username' ORDER BY id DESC LIMIT 1");
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
?>
PROFILE VIEW
<br>Name: <?php echo $row['nombre']?> ID: <?php echo $row['Age']?> <br />
<?php
}
?>
All working fine. If somebody can make it safer, I'd appreciate it.
I'd go with this.
<?php
$host = "localhost";
$username = "db_user";
$password = "db_pass";
$dbname = "db_name";
$db = mysqli_connect($host, $username, $password, $dbname);
if(mysqli_connect_errno()) {
die("Connection could not be established");
}
$username = $_GET['user'];
$query = $db->prepare("SELECT * FROM `members` WHERE `profile` = ? ORDER BY `id` DESC LIMIT 1");
$query->bind_param('s', $username);
$query->execute();
while($row = $query->fetch_row()) { ?>
<br />Name: <?php echo $row['nombre']; ?> ID: <?php echo $row['Age']; ?> <br /><?php
} ?>

Categories