Insert output data to database of an web page - php

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.

Related

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>
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;

What am I missing with php command to INSERT INTO SELECT FROM?

I have a database and it contains four tables (for the sake of security I gave them disney character names) named huey, dewey, lewey and uncledonald.
I would like to have the data from the columns deweysays in the table dewey, hueysays from the table huey and leweysays from the table lewey to show up in thier corresponding columns in the table uncledonald. See attached pic to see visually what I mean.
4 tables
I've tried the following code and get the result I want but only once. After that I get data in the dewey, huey and lewey tables but nothing else in the uncledonald table.
<?php
//Let's see whether the form is submitted
if (isset ($_POST['submit'])) {
$con=mysqli_connect("localhost","root","root","provingground");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO dewey (lot_id, deweysays) VALUES (0, '{$_POST['deweyspeak']}');";
$sql .= "INSERT INTO huey (cust_id, hueysays) VALUES (0, '{$_POST['hueyspeak']}');";
$sql .= "INSERT INTO lewey (personal_id, leweysays) VALUES (0, '{$_POST['leweyspeak']}');";
$sql .= "INSERT INTO uncledonald (deweysays) SELECT deweysays FROM dewey ";
$sql .= "INSERT INTO uncledonald (hueysays) SELECT hueysays FROM huey ";
$sql .= "INSERT INTO uncledonald (leweysays) SELECT leweysays FROM lewey ";
// Execute multi query
if (mysqli_multi_query($con,$sql)){
print '<p> The Ducks Have Spoken.</p>';
} else {
die ('<p>Could not add entry because:<b>' . mysqli_error() . '</b>.</p><p>The query being run was: ' . $sql . '</p>');
}
}
mysqli_close($con);
?>
Is there something missing in my $sql query to uncledonald? Please help!

Storing Data to MySQL database from html form with checkboxes

I have an html form with checkboxes and I managed to store the values using an array to my database .
I added a name field to the form, and added a column on mysql table .
The problem is, the newly added name field is not storing any values and is malfunctioning the previous code. I'm pretty sure my definition for the $fname value is incorrect, here is the full php code
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
if (!$dbcon) {
die('error connecting to database'); }
echo 'Courses successfully registerd , ' ;
// escape variables for security
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$fname = $_POST["name"];
// Get Cources
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
//$ckb = join (', ', var_dump($_POST['ckb']));
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
if (!mysqli_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysqli_close($dbcon);
?>
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
is your problem. You are attempting to insert three values into two fields. You need to add your new field after ckb so that the argument $fname can be inserted into it.

PHP not inserting some values into MySQL database

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [blank]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
Well it will insert the final value only , because you are executing the $sql and the last values of $sql is "INSERT INTO scores (result) VALUES ('$_POST[result]')"; You are overiding the previous values by putting same variable name.
Also (!empty($_POST[hometeam])) remove the !empty if the fields can be blank sometimes.
You are overwriting your SQL statements each time. Beacue your 'result' field isn't blank, you are setting your SQL statement to:
"INSERT INTO scores (result) VALUES ('$_POST[result]')"
This is the only statement which is then being executed - your other values are being ignored as they are not part of this statement.
What you need to do is set up your variables first:
$hometeam = isset($_POST['hometeam']) ? $_POST['hometeam'] : NULL;
$awayteam = isset($_POST['awayteam']) ? $_POST['awayteam'] : NULL;
$result = isset($_POST['result']) ? $_POST['result'] : NULL;
You can then do your database interaction:
$sql = "INSERT INTO scores hometeam, awayteam, result VALUES $hometeam, $awayteam, $result";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
I should say that I haven't included any security on this - you should look into PDO or prepared statements to make sure your database isn't open to SQL Injection.
Hope this helps!
First off, there's a huge security flaw in this code, which is not sanitizing your inputs. A user could insert whatever they like and it's executed on the DB without any checking. This is bad.
At the very least, you should be using something like mysql_real_escape_string(), even though even that is not exactly the best thing for the job (Google PHP + PDO for example).
Secondly, you're actually executing one query using one variable. If $_POST['result'] is set, then $sql will always be the last value. What you might want to do is make the query like so:
$query = 'INSERT INTO scores ('.$fields.') VALUES ('.$values.')';
And construct the $fields and $values variables using your if(!empty( .. )) code.
But to reiterate SANITIZE YOUR INPUTS
3 insert into statements will insert 3 records, with unspecified fields left as null or default.
you must use 1 insert into statement, something like:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
#$sql="INSERT INTO scores (hometeam,awayteam,result) VALUES ('{$_POST[hometeam]}','{$_POST[awayteam]}','{$_POST[result]}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
here, unspecified values will come as empty string, if that is a problem, first assign them to 3 seperate variables with ifs (e.g. set empty ones to null), then use them
I think there is some problem with the declaration of name of your input field in you html form. Make sure, $_POST[hometeam] must be the same input name in your form
Example:
In your form
<input type="text" name="hometeam" value="" />
In your PHP
if (!empty($_POST[hometeam])) {
$sql="INSERT INTO scores (hometeam) VALUES ('$_POST[hometeam]')";
}
And also, please use addslashes or mysql_real_escape_string in your post values before adding it on the database.
Look at this link below:
http://php.net/manual/en/function.addslashes.php
http://php.net/manual/en/function.mysql-real-escape-string.php
if (!empty($_POST['hometeam'])) {
$sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
}
Notice the single quotes around the 'hometeam' part.
You should also clean that using mysql_real_escape_string($_POST['hometeam']).
Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).

How do I store generated Id from last query into a table in php

Hi how can I store a generated id from my last query to another table in mysql using php?
Here is my code (what seems to be wrong in it?
$regInfo = "INSERT INTO details (name, age_range_ID, sports) VALUES ('{$clean_name}', {$clean_age_range}, '{$clean_sports_list}')";
if (!mysql_query($regInfo ,$link))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$regId = mysql_insert_id();
$modInfo = "INSERT INTO module_info (reg_ID, programme) VALUES ('{$regId }', '{$clean_programme}')";
if (!mysql_query($modInfo ,$link))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($link)
This really isn't the best way to be doing this, it's not 1999 you know...
So try looking into Mysqli. If you google this topic, you'll get a bunch of tutorials on how to work with it.
And just to fix your problem for the time being, try this:
<?php
$regInfo = "INSERT INTO details (name, age_range_ID, sports) VALUES (`$clean_name`, `$clean_age_range`, `$clean_sports_list`)";
if (!mysql_query($regInfo ,$link))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$regId = mysql_insert_id();
$modInfo = "INSERT INTO module_info (reg_ID, programme) VALUES (`$regId`, `$clean_programme`)";
if (!mysql_query($modInfo ,$link))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($link);

Categories