I am currently trying to send data from an HTML form (Proform.html) to a MYSQL database. I cannot figure out how to solve this problem that keeps occurring as I am new to php the error message I keep receiving is.
"Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\php\Proform.php on line 22"
It could be possable as I have used several different references to create this page of code that i have mixxed two different realeases of php. Though help would be appriciated Anyways code is as follows.
<?php
$dbname='*****';
$dbhost='localhost';
$dbpass='******';
$dbuser='******';
$dbhandle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("ecig",$dbhandle)
or die("Could not select examples");
$q = $dbhandle->query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)");
if (array_key_exists ('check_submit', $_POST ))
echo "Your Name is : {$_POST['First_Name']}<br />";
echo "Your Second Name is : {$_POST['Second_Name']}<br />";
echo "Your Email Address is : {$_POST['Email_Address']}<br />";
echo "Your Password Is : {$_POST['Password']}<br />";
?>
There is a problem in your query
Why are you calling the query using the database connection string.
You have to call it like this:
$con=mysql_connect($dbhost,$dbuser,$dbpass,$dbname);
$res=mysql_query("INSERT INTO Persons (First_Name, Last_Name) VALUES('$_POST[First_Name]', yes)");
mysql_close();
mysql_connect does not return any object .... so it does not have any function or property that you can access using -> operator . It returns a connection identifier
replace
$dbhandle->query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)");`
with
mysql_query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)")
I advice you to start learning mysqli or PDO since mysql functions are retarded and no longer maintained
Related
Can anyone help with advising what may be wrong with my insert into syntax please ?
Working except i am receiving empty query message
// values sent from form
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$postcode=$_POST['postcode'];
$gender=$_POST['gender'];
$yob=$_POST['yob'];
/*********** CONNECT TO THE DATABASE ******/
//Step 1 CONNECT TO THE DATABASE
$db=mysql_connect ("localhost", “db_username, “db_password);
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
//Step2 SELECT THE DATABASE
$db_select = mysql_select_db(“db_name,$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
echo "Welcome $first_name!";
echo " Success, connected to database but maybe not the table";
// Insert data into database
//##############################I THINK PROBLEM MUST BE HERE IN THIS INSERT STATEMENT STATEMENT###################################
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
if(mysql_query($sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($db);
}
$result=mysql_query($sql);
Your query,
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
Your new query,
$sql = "INSERT INTO `newsletter-subscribers` (first_name, last_name, email, postcode, gender, yob) VALUES ('$first_name','$last_name','$email','$postcode','$gender','$yob')";
So, what has changed?
Added ticks around your table name.
Removed spaces which you didn't need to make query clearer.
Without the backticks around your table name, MySQL is treating it as newsletter minus subscribers. Which is wrong, add the ticks to tell MySQL that it is a table name.
Edit 1
This might be a copy & paste error, I'm not sure, however...
Your db connect is incorrect too, you aren't assigning any values to it as your quotes are not closed and are smart quotes.
Your connect,
$db = mysql_connect ("localhost", “db_username, “db_password);
Your new connect,
$db = mysql_connect("localhost", "db_username"," db_password");
Also,
$db_select = mysql_select_db(“db_name,$db);
To,
$db_select = mysql_select_db("db_name", $db);
Notice the difference in the quotes.
Edit 2
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Not to mention your $_POST data is being passed on to the query without being sanitized, you should start using htmlspecialchars it would make it better and prevent XSS.
Your table name contains a dash, so you need to quote it. The backtick or back-quote character is used to quote symbol names in MySQL (such as the names of tables, columns, etc), so you would need something like this:
INSERT INTO `newsletter-subscribers` (first_name, ...
Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?
<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
echo 'Connected to MySQL server successfully.</br>';
else
echo 'Unable to connect to server</br>';
$database = mysqli_select_db($myConn,$myDB);
if($database)
echo 'Connected to database...</br>';
else
echo 'Database not found!</br>';
$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));
?>
You have to add single quotes around the values:
$query= "INSERT INTO users VALUES ('$var1','$var2')
Or better use prepared statements. See this for an example.
In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:
$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";
if users table have only two columns, or two plus an auto-incrementing id the query is:
INSERT INTO users VALUES ('$var1','$var2')
if there are more columns or a non primary id the query is:
INSERT INTO users (col1,col2) VALUES ('$var1','$var2')
You also miss a parameter in the connection instantiation:
$mysqli = new mysqli($host, $uname,$pswd, $myDB);
$value2=$_POST['c_name'];
$value3=$_POST['c_vehicle_number'];
$value4=$_POST['c_phone'];
$value5=$_POST['c_email'];
these are the values stored in 1.php.
i want insert those values in 2.php.as below,
$sql="insert into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) values ('','$value2','$value3','$value4','$value5')";
=====================================================
am using require('1.php');
which does not insert the values into the database.
what would be the soluton.?
In order to enter a values into the DB one must have a connection to the Database.
Create a connection to the relevant database.
Perform our desired query.
Example:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Explanation:
As you can see we first trying to retain a connection using mysqli_connect with the relevant DATABASE-ADDRESS, USERNAME, PASSWORDandDATABASE-NAME`
Than we're using mysqli_query to perform our query and we're passing it the connection we opened earlier + the query string we wish to perform.
More explanation could be found HERE
Important: This example isn't SQL-Injection protected, and it's highly important to you, to be protected against it. Read about it HERE
you can try this
$sql="INSERT into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) VALUES ('".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."')";
you worte :
('','$value2','$value3','$value4','$value5') you did mistake here
it can be write
('".$value2."','".$value3."','".$value4."','".$value5."')
I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...
I can get it to work from home which I coded using mysqli but my school doesn't have that enabled so now it wont execute the query what am I doing wrong or is there a better way of doing this?
!!!Update!!!
So I connected to my website at home the one that works and redid the connection by just removing the i form the connections and the extra field (database name) in $dbc and it started getting errors. this happened even before I removed the database name from the connection. So I realized that the script doesn't know what database I'm connecting to. How can I fix this?
Home (works)
/* database connection */
$dbc = mysqli_connect('localhost', 'user', '9890667', 'zombies')
or die('Error Connecting to the MySQL Server');
/* insert query */
$query = "INSERT INTO zombie_sighted (first_name,last_name, when_it_happened, how_long, how_many, zombie_description, what_they_were_doing, fang_spotted, other, email) " .
"VALUES ('$first_name','$last_name','$when_it_happened','$how_long','$how_many','$zombie_description','$what_they_did','$fang_spotted','$other','$email')";
/* execute query */
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
School(connects but query doesn't work now) Updated
$dbc = mysql_connect('shcool url', 'username, 'password')
or die('Error Connecting to the MySQL Server');
/* insert query */
$query = "INSERT INTO zombie_sighted (first_name,last_name, when_it_happened, how_long, how_many, zombie_description, what_they_were_doing, fang_spotted, other, email) " .
"VALUES ('$first_name','$last_name','$when_it_happened','$how_long','$how_many','$zombie_description','$what_they_did','$fang_spotted','$other','$email')";
/* execute query */
$result = mysql_query($dbc, $query)
or die('Error querying database.');
mysql_close($dbc);
Are you certain localhost is the correct MySQL path at your school location? If this is a shared server that doesn't allow things like shell access I bet the db path is not localhost as it would be on a dedicated box.
$result = mysql_query($query) try this.
mysql_query
you pass the resource in as first param when the query string is supposed to be. also, make sure your mysql_connection fields are correct.