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>
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
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 https://stackoverflow.com/a/3531852/3234646
4.Please clear Concept use of Database Extension
http://php.net/manual/en/class.mysqli.php
You forgot to execute the query, if ($sql) { merely evaluates the variable.
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Also, you need to use backticks for SQL-related variables, not single quotes:
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');";
You're not actually executing your query. If you add the line $result = mysqli_query($link, $sql); after declaring $sql you will execute the query.
You can then assess whether it worked using the same if, but change that line to be
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
In the above example, I have also changed your error reporting as it was referencing $conn, a variable you had not declared before. It now uses the same $link variable as the rest of your code.
Also, I would highly recommend escaping your data since you're inserting the contents of posted data. Escaping your data will help protect against SQL Injection. It's not comprehensively safe, but it's a good start.
To add in escaping, change each $var = $_POST['var'] line to read $var = mysqli_real_escape_string($link, $_POST['var']);
For example, $hos=$_POST['hos']; becomes $hos = mysqli_real_escape_string($link, $_POST['hos']);
This helps prevent moments like this wonderful example by XKCD
1) Remove single quotes (') from column name to backtick (`)
2) Execute your query. You didn't executed.
3) If app_id column is auto incremented and primary key. Then, no need to pass value. Leave it blank.
<?php
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('','$pat','$date','$time','$hos','$doc');";
$query = mysqli_query($link,$sql) ;
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Instead of
"INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');"
unquote the columns
"INSERT INTO rantevou (app_id, patient_id, date, time, hos, doc) VALUES ('4','$pat','$date','$time','$hos','$doc');"
or use backticks
"INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');"
you've forgot to execute your query
mysqli_execute($con, "INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc')");
EDIT: What luweiqi said: the statement has yet to be executed!
It seems like you know what you are doing. Are you sure that the paramaters here:
$sql = "INSERT INTO rantevou (**'app_id','patient_id','date','time','hos','doc'**) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
exactly match your column titles in your database?
Another good way to check your statements, is to go to phpmyadmin and go to the SQL notepad and enter the query with the same structure and see what is being returned.
Your query may be returning a message, but a message saying that it has failed... which would still trigger your echo "New record created successfully";
This is how i've structured my most recent insert to DB:
<?php
// to get data from android app
$gardenID=$_POST["gardenID"];
$vID=$_POST["vID"];
$quantity = $_POST["quantity"];
$timePlanted = date("Y/m/d");
// establishes connection to database
require "init.php";
echo "here";
echo $timePlanted;
echo $quantity;
$query = "insert into garden_veg (gardenID, vID, quantity, timePlanted) values ('".$gardenID."','".$vID."',
'".$quantity."', '".$timePlanted."' );";
$result = mysqli_query($con,$query);
$response = array();
$code = "addItem_success"; //changed code
$message = "Item(s) added!";
array_push($response,array("code" => $code, "message"=>$message));
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
First of all, don't use single quotes for column names, either use nothing or use backticks.
Secondly, you forgot to execute the query.
Also, using OOP is better.
Please try:
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
and
$query = "INSERT INTO rantevou (app_id,patient_id,date,time,hos,doc) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($mysqli->query($query)) echo "New record created";
else echo "Error: ".$mysqli->error;
Related
<?php
$con=mysql_connect('localhost', ' ', ' ') ;
$db=mysql_select_db(' ') ;
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST'mobile'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (name, email, mobile)
VALUES ('$name', '$email', '$mobile')";
if ($con->query($sql) === TRUE)
{
echo "New record created successfully";
}
else{
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>`
i am trying to insert data into my table but it throwing a error
help me to solve this problem .
my error:
syntax error, unexpected ''mobile'' (T_CONSTANT_ENCAPSED_STRING)
This is suppposed to be a comment, but i have a low reputation here.
Before i answer your question, please do not use the mysql functions as its no longer supported . Consider a switch to either MYSQLI or PDO. Also, do not trust user input. Meaning do not directly post field values from your form to your database as an attcker can easily exploit it by adding funny javascripts or worse.
It wont work because, you forgot to open the square brackets,
$mobile = $_POST['mobile'];
To your question, try this:
$sql = "INSERT INTO user (`name`, `email`, `mobile`)VALUES
('".mysqli_real_escape_string($con,$_POST['name'])."',
'".mysqli_real_escape_string($con,$_POST['email'])."',
'".mysqli_real_escape_string($con,$_POST['mobile'])."')";
where the variable $conn is your database connection
$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When i do this only the first row will be added. How do i insert multiple rows?
Just get rid of that multi query thing. Use a prepared statement instead
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.
You are overwriting the query each time. Try setting sql to blank then appending it each time in the loop.
Try this:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You don't need to perform the query multiple times like that, you can do it all in a single query without multi_query(). You can perform many INSERTs with a single query, like this
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will generate a query resembling
INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
which will insert the values One, Two and Three into separate rows.
This query will break if your $game['name'] variables contain an apostrophy ', so at the very least you should use $mysqli::real_escape_string(), although a prepared statement takes care of that and prevents SQL injection (so I recommend you go for that instead). See How can I prevent SQL injection in PHP?
Using a prepared statement - the better solution
The preferred method of executing a query is by using a prepared statement.
Fetch all the columns using array_column() and loop the array while calling the execute method until finished.
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}
can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}
Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
COMMIT; You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'INSERT INTO our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...
i have a output page of the following php code..
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
the output value of the script is to be inserted in to the database like MySQL.
for that i try something like that..
<?php
// example of how to use basic selector to retrieve HTML contents
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE nt_usawine",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("nt_usawine", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
$foo= $data[2];
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)");
mysql_close($con);
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
but still i cant get the table in the database with my data inserted. what is the right way to save the data ?
Have you tried to debug this by using mysql_error ?
$query = "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)";
$result = mysql_query($query);
if (!$result) {
$message = 'There is an error : ' . mysql_error() . "\n";
$message .= 'The query was : ' . $query;
die($message);
}
If you have an SQL error this would be very usefull.
By the way have you seen the only once time you don't do mysql_query( [...], $con) it the once which should add datas ?
And is it normal that you create a database and a table each time ? (don't know what you really want to do)
The mysql_query(); function allows you to run a query. Using the INSERT syntax you can insert data.
Example:
mysql_query("INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')");
Currently, what I'm seeing you wish to insert the country, email, postal address, permanent address and contact even though you create a table that can hold the data firstname, lastname and age...
No offence, but if you're already stuck there, this is not the right place to post your question. You need to search some tutorials before you even consider asking. SQL queries are well documented and can be found all over the web.
Either way, I'm too kind to leave this question unanswered.
I advice to create your database and table in PhpMyAdmin, rather creating a new one in your script. It's rather inefficient.
<?php
// this is where you login to your database
$connection = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
// select your EXISTING database you created. Usually there's a single database linked to your website
mysql_select_db('database_name', $connection);
// inserting data into table
$success = mysql_query("INSERT INTO `table_name` (`country`, `email`, `postaladdr`, `permanentaddr`, `contact`) VALUES ('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[2])."', '".mysql_real_escape_string($data[3])."', '".mysql_real_escape_string($data[4])."', '".mysql_real_escape_string($data[10])."')");
// check if insert was successful
if($success) {
echo 'data inserted';
} else {
echo 'Something went wrong: ' . mysql_error();
}
// closing database
mysql_close($connection);
?>
Now all you have to do is change the login data, change the database_name, create the actual table and change the table_name in the script.
This is one of the first things you learn when starting with running SQL queries, so I higly suggest to learn more: http://www.w3schools.com/php/php_mysql_intro.asp
If everything I said didn't make any sense, you should click the link above.