I am trying to insert some data into my database with this code:
$username = $_SESSION['user'];
$naslov = $_POST['naslov'];//name
$geslo = $_POST['geslo'];//password
$vsebina = $_POST['vsebina'];//description
if (trim($_POST['naslov'])=="" || $_POST['geslo']=="" || $_POST['vsebina']==""){
$status = "<div class='alert-danger'>Fields are empty</div>";
}
else{
$link = open_database_connection();
echo $username;
echo $naslov;
echo $geslo;
echo $vsebina;
$sql = "INSERT INTO projects (name, password, description, username) VALUES ('$naslov','$geslo','$vsebina','$username')";
mysqli_query($link, $sql);
close_database_connection($link);
$status = "<div class='alert-success'>Vic je bil dodan.</div>";
}
The echo show the values i am putting into the forms, the SQL does not show any errors it just doesn't insert the values into the table.
check if form method is POST if its not then change the code to
$username = $_SESSION['user'];
$naslov = $_GET['naslov'];//name
$geslo = $_GET['geslo'];//password
$vsebina = $_GET['vsebina'];//description
if (trim($_GET['naslov'])=="" || $_GET['geslo']=="" || $_GET['vsebina']==""){
$status = "<div class='alert-danger'>Fields are empty</div>";
}
else{
$link = open_database_connection();
echo $username;
echo $naslov;
echo $geslo;
echo $vsebina;
$sql = "INSERT INTO projects (name, password, description, username) VALUES ('$naslov','$geslo','$vsebina','$username')";
mysqli_query($link, $sql);
close_database_connection($link);
$status = "<div class='alert-success'>Vic je bil dodan.</div>";
}
Related
addmember.php
<?php
require_once("dbtools.inc.php");
$account = $_POST["account"];
$password = $_POST["password"];
$name = $_POST["name"];
$sex = $_POST["sex"];
$year = $_POST["year"];
$month = $_POST["month"];
$day = $_POST["day"];
$telephone = $_POST["telephone"];
$address = $_POST["address"];
$email = $_POST["email"];
$comment = $_POST["comment"];
$link = create_connection();
$sql = "SELECT * FROM users Where account = '$account'";
$result = execute_sql($link, "member", $sql);
if (mysqli_num_rows($result) != 0)
{
mysqli_free_result($result);
echo "<script type='text/javascript'>";
echo "alert('Account already in use! Please choose another username');";
echo "history.back();";
echo "</script>";
}
else
{
mysqli_free_result($result);
$sql = "INSERT INTO users (account, password, name, sex,
year, month, day, telephone, address,
email, comment) VALUES ('$account', '$password',
'$name', '$sex', $year, $month, $day, '$telephone',
'$address', '$email', '$comment')";
$result = execute_sql($link, "member", $sql);
echo "User added successfully!";
}
mysqli_close($link);
?>
join.html
<form action="addmember.php" method="POST" name="myForm">
(Different types of input)
<input type="submit" value="Add">
My aim is to add a member data into the database after the user clicked the Add button on the form in join.html. However the page could run echo "User added successfully!"; this line but the problem is the database could not get updated even though I already called execute_sql command. May I ask what is missing in order to be connected with the database?
The code I have below is suppose to insert some information into a mysql database. For some reason every time I test it I get the error statement that it was not able to execute. Everything looks like it should work to me. Is there something I am missing here?
<?php
include("phpconnect.php");
$name = $_GET["name"];
$date = $_GET["date"];
echo $name;
echo $date;
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES ('$name', '1', '$date', '$date')";
if (mysqli_query($conn, $sql))
{
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not execute $sql. "
.mysqli_error($conn);
}
mysqli_close($conn);
?>
Maybe, you should build your SQL statement slightly different. You can always throw an error message, better for the overview -
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES (?, 1, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('sss', $name, $date, $date);
if (!$stmt->execute()) {
return false;
// or print error message
} else {
return true;
} else {
return false;
}
Or check this out - MySQL INSERT INTO with PHP $variable !
First Check your datbase connection
Second check your form method GET or POST then apply
Check your table column name
include("phpconnect.php");
if(isset($_POST['submit'])){
$name = $_POST["name"];
$date = $_POST["date"];
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit) VALUES ('$name', '1', '$date', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Try something like this. This function accurately inserts into my database and also scrapes for SQL injection.
function addRestaurant() {
if(isset($_POST['submit'])) {
global $connection;
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$googlemapslink = $_POST['googlemapslink'];
$restauranttype = $_POST['restauranttype'];
$website = $_POST['website'];
$logo = $_POST['logo'];
$sitelink = $_POST['sitelink'];
if ($googlemapslink == "") {
$googlemapslink = "https://youtu.be/dQw4w9WgXcQ";
}
if ($website == "") {
$website = "https://youtu.be/dQw4w9WgXcQ";
}
if ($logo == "") {
$logo = "https://youtu.be/dQw4w9WgXcQ";
}
$name = mysqli_real_escape_string($connection, $name);
$address = mysqli_real_escape_string($connection, $address);
$city = mysqli_real_escape_string($connection, $city);
$state = mysqli_real_escape_string($connection, $state);
$zipcode = mysqli_real_escape_string($connection, $zipcode);
$googlemapslink = mysqli_real_escape_string($connection, $googlemapslink);
$restauranttype = mysqli_real_escape_string($connection, $restauranttype);
$website = mysqli_real_escape_string($connection, $website);
$logo = mysqli_real_escape_string($connection, $logo);
$sitelink = mysqli_real_escape_string($connection, $sitelink);
$query = "INSERT INTO `restaurants` (Name, Address, City, State, ZipCode, GoogleMapsLink, Website, RestaurantType, RestaurantLogo, SiteLink) ";
$query .= "VALUES (";
$query .= "'$name', ";
$query .= "'$address', ";
$query .= "'$city', ";
$query .= "'$state', ";
$query .= "'$zipcode', ";
$query .= "'$googlemapslink', ";
$query .= "'$website', ";
$query .= "'$restauranttype', ";
$query .= "'$logo', ";
$query .= "'$sitelink'); ";
$filesite = "restaurants/" . $sitelink;
$file = "restaurants/menu.php";
$contents = file_get_contents($file);
file_put_contents($filesite, $contents);
$result = mysqli_query($connection, $query);
if(!$result) {
die("Query failed." . mysqli_error($connection));
} else {
echo "Record updated!";
}
}
}
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
Ho can I check the database first if a user exists then use a insert statement if it does not. The code currently only executes the select statement.
<?php
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_query($dbconn, $query_check_user)) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
<?
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
//Query for count
$query_check_user = "SELECT count(*) as total FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
//Execute query for count
$result = mysqli_query($dbconn, $query_check_user);
//Fetch result
$data = mysqli_fetch_assoc($result);
//Check if count >0
if ($data['total']>0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
you can use mysqli_num_rows(); to check the number if result if it is greater then 0 then user exist else insert user data.
my example :
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query_result = mysqli_query($query_check_user);
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_num_rows($query_result) > 0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
as I get from your question is, you want to insert the user if the user doesn't exist, right?
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$b = mysqli_query($dbconn,$query_check_user);
$a = mysqli_num_rows($b);
if($a<0):
mysqli_query(dbconn, "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')");
endif;
This is my php code for insert account into the table
<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "insert into account_data (username,password) values ('$user_name','$user_pass')";
$result = mysqli_query($conn ,$mysql_qry);
if($result) {
echo "insert success";
}
else {
echo "Failed insert of '$user_name', '$user_pass' ";
}
?>
And this is the php for login
<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from account_data where username like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "Accesso riuscito";
}
else {
echo "Accesso non riuscito: username ($user_name) o password ($user_pass) non corretti ";
}
?>
I can't understand why the second code works perfectly and the second one doesn't work, any ideas?