SQL error (ERROR: Could not able to execute INSERT INTO) [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I have a database that I have made on phpmyAdmin that consists of three columns: id, name and number.
I have added 3 rows of data to the database through phpmyadmin.
I now wish to add data to this database through my php file. This is the code that I use to add in the data and display the data on the browser:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myfirstsite";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
$sql = "INSERT INTO hi (id, name, number)
VALUES ('99', 'Doe', '999999')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//displaying data
$sql = "SELECT id, name, number FROM hi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["number"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The thing is that I don't understand why the new data isn't placed into the database but the current data is displayed onscreen.

In your code you are making reference to $link which doesnt exists, it should be $conn
Chaneg this:
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
To:
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

you need to fix this one
$conn = new mysqli($servername, $username, $password, $dbname);
to
$conn = new mysqli_connect($servername, $username, $password, $dbname);
and also this need to fix
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}

Related

How can i display a success pop up message before redirecting a user to the last php page

I want to have a pop up window appear to let people know that sending their comment was successful. Once they click on the OK button then they get redirected to the last page that they were on. I can get the alert to work if I remove the last line but they just don't work together. Using my code below the alert message is skipped and it goes directly to the referrer line. I have no idea why. I would really appreciate your help. Thanks.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$target_file','2')";
if ($conn->query($sql) === TRUE) {
$message = "Thankyou for your comment.";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
header('Location: ' . $_SERVER['HTTP_REFERER']);
You cannot output anything before a header() call as it will cause header already sent error.
Made the redirection using a js code.
Try this:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$target_file','2')";
if ($conn->query($sql) === TRUE) {
$message = "Thankyou for your comment.";
echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script type='text/javascript'>
window.location = '".$_SERVER['HTTP_REFERER']."';
</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
You can try this, it will redirect to the previous page 3 seconds after the alert goes up (3000ms)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO comment (Comment, firstname, lastname, Image_path, Approved)
VALUES ('$comment', '$firstname','$lastname','$target_file','2')";
if ($conn->query($sql) === TRUE) {
$message = "Thankyou for your comment.";
echo "<script type='text/javascript'>alert('$message');</script>";
echo "function goBack() { setTimeout(function(){ window.history.back(); }, 3000);}";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();

I am trying to run a query that takes value from one table and uses it as condition to fetch value or execute action on another table

I am trying to take the value of the topay column where torecieve equals to current session user id and use it to perform operation on the user table.
But it throws a syntax error
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bazze2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$merge = "SELECT topay FROM merge WHERE torecieve=$_SESSION[id]";
$sql = "UPDATE user SET topay2='10000000' WHERE 'id'=$merge";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Use a prepared query, and use a join.
$sql = "UPDATE user AS u
JOIN merge AS m ON u.id = m.topay
SET u.topay2 = '10000000'
WHERE m.toreceive = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_SESSION['id']);
if ($stmt->execute()) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $stmt->error;
}

Delete Page PHP MYSQL

Hey guys I have created A delete page, It does not work when I just submit the form and the URL is http://localhost/delete-session.php but once I change the URL to http://localhost/delete-session.php?id=1 it works, What am I missing In my code to make it work?
<h1>Delete Page</h1>
<h3>Enter the booking number of the session you would like to delete!</h3>
<form action ="delete-session.php" method="post">
Booking ID:(Refer To Database):<input type="text" name="booking">
This is the php
if(isset($_GET['booking'])){
$id=$_GET['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error.";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id=$_GET['id'];
if(!is_numeric($id)){
echo "Sorry, there is an error";
exit;
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
echo $sql;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
I'm going to take a crack at this.
I'm guessing it's because when you go to http://localhost/delete-session.php?id=1 you're passing the id=1 via GET, so when you retrieve the GET input from in your code it succeeds with $id=1, but in your HTML your form is send via POST.
As a fix try using $id=$_POST['booking'];
Bench test your code.
It starts getting $id=$_GET['booking']; which does not exist because you have set the method="post" in your <form> tag.
So use $id=$_POST['booking'];
Then later on it does $id=$_GET['id']; overwriting the value you already attempted to get from above.
This would explain why it requires the extra id paramter on http://localhost/delete-session.php?id=1 as using the querystring to send data will send the id parameter in the $_GET['id'] array, and I dont see why you would want to do this anyway as it has been done at the top of your code by getting this id value from $id=$_POST['booking']
It also makes code so much easier to read and more importantly debug if you adopt an indentation standard in your script like below.
Try this out for size, without adding the id=1 to the querystring
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
$res = mysqli_query($conn, $sql);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
As you are using the mysqli extension, you should also be using parameterized queries to prevent SQL Injection.
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking=?";
$stmt = mysqli_prepare($conn, $sql);
if ( $stmt === FALSE ) {
echo mysqli_error($conn);
exit;
}
mysqli_stmt_bind_param($stmt, 'i', $id);
$res = mysqli_stmt_execute($stmt);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Change form method to get, or use $_REQUEST instead of $_GET

Php to MySQL database

I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}

mysql query unable to update

Mysqli query not updating table with custid
// Create connection
$db = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$db) {
die("Connection failed: " . mysqli_connect_error());
}
//$query = "Select expiry from AcctSession where id ='$id' ";
echo $custid.$id; //works fine here
$query = "update sessions SET custid = '$custid' where id = '$id' ";
if (mysqli_query($db, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db);
}
I've tried echoing $query
Query works fine on command line but it doesn't write any result when firing from php script(Plus, no error msg as well)

Categories