Having hard time querying database - php

I'm trying to insert data in mysql using php I have FK with parishionerID
my query is correct but I always get the Error querying database. It doesn't show me
the specific query that I'm having an error with. BapID is PK. Hope you can help me resolve this. Thanks.
$con = mysqli_connect('localhost', 'root', '', 'RMS') or die('Error connecting to MySQL server');
$sql="INSERT INTO baptismal (ParishionerID, BapID, Datebaptism, Ministerbaptism, Sponsor, Sponsor2, Volume, Page)
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
$result = mysqli_query($con, $sql) or die('Error querying database.');
mysqli_close($con);
If I input datas in mysql manually this is the query which is pretty have the same with my query.
INSERT INTO `rms`.`baptismal` (`ParishionerID`, `BapID`, `Datebaptism`, `Ministerbaptism`, `Sponsor`, `Sponsor2`, `Volume`, `Page`) VALUES ('80', NULL, '2014-07-16', '131', 'sdasd', '123123', '123123', '123');

There seems to be only Syntax error. Youre missing '
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
----------------------------------------------------------------------^

Your $Sponsor2 is not properly quoted.
FYI: Let the script print out the error SQL too.
Convert your line as:
$result = mysqli_query($con, $sql) or die('Error querying database: '.$sql);
Then, you will see the exact query that ran.
Do not print SQLs on the server mode.

Related

mysql_insert_id() not returning a value -

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

add values to mysql database using php on ubuntu

n00b learning php from a book.
I'm trying to add data to a database called adv_php. I'm using the following snippet of code in the page that's receiving the data from the post:
<?php
$dbc = mysqli_connect('host', 'name', 'password', 'adv_php');
if (mysqli_connect_errno())
{
echo "Failed to connec to MySQL" . mysqli_connect_error();
}
$parent_id = $_POST['parent_id'];
$task = $_POST['task'];
// Add the task to the database.
$q = "INSERT INTO (parent_id, task) tasks VALUES ($parent_id,'$task')";
mysqli_query($dbc, $q);
?>
I know this code connects to the database elsewhere as I can retrieve info from the database. With this page, I don't get an error, I just get a blank page, and nothing is added to the database Where am I going wrong?
Your query is wrong...Change it ...
$q = "INSERT INTO tasks(parent_id, task) VALUES ($parent_id,'$task')";
you misplaced table_name, use below query
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";
Your insert statement is wrong
Try this
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

Cant insert data into second database connection

See the code below, there are two databases connections.
First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list'
When I tried SQL query manually in phpMyAdmin and it work fine...
$db_new = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("menu_new", $db_new)) {
die("Cant connect menu_new DATABASE");
}
$db_old = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("old_menu", $db_old)) {
die("Cant connect old_menu DATABASE");
}
$SQL_old = "SELECT * FROM old_table";
$q = mysql_query($SQL_old, $db_old);
while ($row = mysql_fetch_assoc($q)) {
$name = $row['name'];
$SQL = "INSERT INTO tbl_name (fullname) values ('$name')";
//Problem Here - It wont insert into second database
mysql_query($SQL, $db_new) or die(mysql_error($db_new));
}
Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion.
It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server.
Thanks #Konerak for suggestion and that does work!
To Insert/Select data from Database connection, you will have to include database name before the table name.
For Example
From:
mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
To:
mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
That is really odd though.

Whats wrong with my connection statement/Insert Query?

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.

Categories