Asking for some Error - php

I've got error
when i fill the form and click the submit
the result was error "Data Gagal Di tambahkan"
Here the code
<?php
include 'koneksi/koneksi.php';
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$nis = $_POST['nis'];
$nama = $_POST['nama'];
$kelas = $_POST['kelas'];
$nilai_ulangan_teori = $_POST['nilai_ulangan_teori'];
$nilai_ulangan_praktek = $_POST['nilai_ulangan_praktek'];
$sql = "INSERT INTO t_siswa VALUES ('$nis',
'$nama',
'$kelas',
'$nilai_ulangan_teori',
'$nilai_ulangan_praktek'
)";
$nilai ="($nilai_ulangan_teori + $nilai_ulangan_praktek)/2";
if (mysql_query($sql)){
header("location:index.php");
} else {
echo'<script type="text/javascript">alert("Data gagal ditambahkan");</script>';
}
}
here the connection
<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "db_uas_pwd_2017";
mysql_connect($host, $username, $password) or die (mysql_error());
mysql_select_db($db);
$mysqli = mysql_connect($host, $username, $password, $db);

Your SQL code is wrong. You need to specify the column names in the SQL code. For example, the SQL should look something like this
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
And, mysql_ has been depreciated and now PHP recommends either using mysqli_ or PDO. For more references, visit the links below :
https://www.w3schools.com/php/php_mysql_insert.asp
https://www.w3schools.com/php/php_mysql_connect.asp
Answer from xXAlphaManXx, 15yr old

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

Can't make CMS admin for my blog

This is the php program I created to insert data into the database.
<?php
include '../includes/config.php';
//Input Data Process
$row = mysqli_fetch_array($query);
if (isset($_POST["post"])) {
$title = $_POST["title"];
$description = $_POST["description"];
$article = $_POST["article"];
mysqli_query($conn, "INSERT INTO post VALUES('','$title','$description','$article')");
header("location:index.php?article");
}
$query = mysqli_query($conn, "SELECT * FROM post");
?>
But when I hit the post button nothing happens in the database.
This is config.php file.
<?php
//Database Connection
global $conn;
$servername = "localhost";
$username = "root";
$password = "";
$db = "my_blog";
$conn = mysqli_connect($servername, $username, $password, $db);
//Check Connection
if (!$conn) {
die("Connection Failed : ".mysqli_connect_error());
}
?>
You are missing the column names in your INSERT. For example:
INSERT INTO post (column1, column2, column3, column4) VALUES ('', '$title', '$description', '$article')
Note: Technically, you can skip the column names if you are adding values for all the columns of the table. In this case, you also need to make sure that the order of the values is in the same order as the columns in the table.

My code does not write anything on the database

This is my CODE, id do not know where is the mistake but this code does not create any information on the database.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM users WHERE Username='$user'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}else{
mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
header("location:begin.html");
}
}
mysql_close();
?>
Forget database name here.
change this:
$selected = mysql_select_db($dbhandle);
With
$selected = mysql_select_db($dbname,$dbhandle);
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
In above code you are not passing any database name to use, you should pass a database name instead of connection link to mysql_select_db($dbhandle);
like
$db_selected = mysql_select_db('foo', $link);
For reference
http://php.net/manual/en/function.mysql-select-db.php
Hi first of all Please use mysqli or PDO as mysql is depreciated and completely removed from PHP7.
Now your problem . You are not included database name in your mysql_select_db. It should be
$selected = mysql_select_db($dbhandle , $databasename) or die(mysql_error($dbhandle));
Always remember try to echo error after any query this will solve your problem in many cases

Data not inserting into database

So I have my form that sends data to my php file that then enters it into the database. Here's the php backend part
<?php
$db = new mysqli('localhost','root','x','app');
$username = $_POST['username'];
$db->query("INSERT INTO people (first_name) VALUES ('{$username}'");
?>
But my question is, why isn't username being put into the database?
You are missing a bracket ) in the following line:
("INSERT INTO people (first_name) VALUES ('{$username}' ")
^ // <= right there
change it to:
("INSERT INTO people (first_name) VALUES ('{$username}')")
Yet, as pointed out in comments, you are open to SQL injection when using your present method.
Use prepared statements, or PDO.
Here follows an example of a prepared statement:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = #mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$mysqli) {
die('Connect Error: ' . mysqli_connect_error());
}
// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$sql = ("INSERT INTO people (first_name) VALUES (?)");
$stmt = $mysqli->prepare($sql) or die("Failed Execution");
$stmt->bind_param('s', $username);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
Plus, using error reporting is important before going live.
http://www.php.net/mysqli_error
Should you want to get into learning PDO,
Here are a few tutorials for you to look into:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Here is a PDO example:
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try{
$db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$email = $_POST['email'];
$username = $_POST['username'];
$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`)
VALUES (:email, :username)");
$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);
$result_set->execute(array(':email' => $email, ':username' => $username));
echo "Data successfully written.";
return $db;
}catch(PDOException $e){
echo $e;
return false;
}
?>
PDO error handling links:
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories