ask2know ask2know - 6 months ago 19
HTML Question

cant insert data into existing table in mysql database with php

I get the message that the new record was created but when I reload phpmyadmin the table is the same. Also I have retrieved information from the same DB,
from the same table, with SELECT command, so the connection works..(plainly said). I have no clue why is not updating. Please help. Thank you in advance.

<html>
<head>
</head>
<body>
<?php
define('DB_NAME', 'appointments');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$link) {
die('Could not connect: ' . mysql_error());
}
$hos=$_POST['hos'];
echo $hos;
echo "<br/>";
$doc=$_POST['doc'];
echo $doc;
$date=$_POST['fdate'];
echo $date;
$time=$_POST['time'];
echo $time;
$pat=5;
echo $pat;
$sql = "INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($link);
?>
</body>
</html>

Answer

There are many mistake in your code

1. use of mysql_error()

you can't use mysql_error because you use mysqli for data base connection.second thing mysql is no more supported

Solution use mysqli_error($link);

2. use of $conn->error

you can't us of $conn->error beacuse you connect with mysqli procedure way not like object oriented way and you also not define a $conn instead you used $link

Solution use mysqli_error($link);

Correct Code

if(!mysqli_query($link, $sql)){
     printf("Errormessage: %s\n", mysqli_error($link));
     die;
}else{
   echo "New record created successfully";
}

Why Data Not Inserted

because you declare variable $sql but you didn't executed that

the new record was created

you get this message all ways because your if condition check that variable have a value (not 0) and yes $sql have value

Remember Few think

1.You must use prepare statement,if you don't wan't any sql injection in insert statement SQL INJECTION

2.'' single quote or "" apply only on a string not on id if your app_id is a int don't use ('' or "") quote instead of that convert '4' to int

3.handle error log http://stackoverflow.com/a/3531852/3234646

4.Please clear Concept use of Database Extension http://php.net/manual/en/class.mysqli.php