I want to insert some info into a table but it doesn't works. This is the code.
<?php
$con=mysql_connect("localhost","Chew","*****","Birthdays");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Name="Something";
$Desc="Something";
$Lang="En";
$D="1";
$M="1";
echo "<br>";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, Day, Month) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
$qr= mysql_query($con, $sql) or die("Error: " . mysql_error());
mysql_close($con);
?>
MONTH and DAY are names of MySQL functions. If you are going to name columns with those names you must escape them with ticks:
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
read mysql_query
$qr= mysql_query($sql, $con) or die("Error: " . mysql_error());
NB: mysql_* is deprecated, use mysqli_* or pdo
If D and M are numbers, your SQL should not use quotes (') in the VALUES-part of your SQL
You should be using Object Oriented mechanism for doing connection with MySQL with the help of MySQLi class
example
// The var's in complete caps means they might be defined as constant variable
// DB_HOST - database hostname
// DB_USER - database user
// DB_PASS - database password
// DB_NAME - database instance name
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db -> connect_error){
// in case there are errors
die("Connect Error (" . $db -> connect_errno . ") " . $db -> connect_error);
}
$Name= mysql_real_escape_string("Something"); // helps to escape special characters like quotes
$Desc= mysql_real_escape_string("Something");
$Lang="En";
$D="1";
$M="1";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', $D, $M );";
$db -> query($sql) or die("Error: " . $db -> error_msg);
echo "Insert id: " . $db -> insert_id;
EDIT: Code to fetch data from database
C_Chewbacc,
I would recommend you on reading more on PHP-MySQL connection using Object Oriented mechanism
http://in2.php.net/mysqli
Try this code below
$sql = "SELECT * FROM Birthdays";
$result = $db -> query($sql); // SELECT query returns result object here
// We iterate over this result object and fetch each row on every iteration
// When the resultant object has nothing to return, NULL is initialised in $row
// When $row = NULL becomes the exit point of WHILE loop
while($row = $db -> fetch_array($result)){
var_dump($row); // This will display every row of data
}
Related
I'm struggling with inserting data from the form to database. I managed to establish the connection (at least not getting any errors), but when comes to inserting values I facing error, I'm not sure if rows/columns of the table should be in ' ' or not, I've seen some examples both with quotation marks and without, and also if variables should have those as well.
connecting to the database (connect.php):
<?php
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","Bookshop");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection){
die("error: unable to connect to database " . mysql_error());
}
$select_db = mysql_select_db(DB_NAME, $connection);
if(!$select_db){
die("error: unable to connect to database " . mysql_error());
}
?>
including connections:
<?php
include ("connect.php"); // connects to database
?>
and inserting data from the form:
$query = "INSERT INTO customer
(CUST_ID, CUST_NAME, CUST_SURNAME, HOUSE_NO, STREET, POSTCODE, PHONE_NO, EMAIL, OGIN, PASSWORD)
VALUES
('10101', '$forename', '$surname', '$address1', '$address2', '$postcode',
'$phone_no', '$email', '$login', '$password')";
mysql_query($query, $connection);
if(!mysql_query($query, $connection)){
echo "Error!!!!";
}
mysql_close($connection);
It seems you are a newbie.. Start with mysqli or pdo extensions. Visit W3schools.com for a detailed explanantion with examples. Below is an example of how to use mysqli to connect and insert a row in your database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
And For your query..
I'm not sure if rows/columns of the table should be in ' ' or not,
I've seen some examples both with quotation marks and without, and
also if variables should have those as well.
As far as insert queries are concerned,
1).Wrap up column names with ` back ticks.
2).Wrap your Variables with single quote nothing wrong in that
For more understanding about single and double quote usages,
Single quotes does not look for variables while double quote does
Case 1 :
$value = 10;
$sql = 'SELECT * FROM `table_name` WHERE `column_name` = $value';
echo $sql;
output is
SELECT * FROM `table_name` WHERE `column_name` = $value
Here if you see single quote does not look for a variable within it. Whatever there is inside single quotes, it is considered as a string and returned as such.
Case 2:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = $value";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = 10
Here Since the query is inside double quotes, That variable is read. but considered as int.
Case 3:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = '$value'";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = '10'
Here Since the query is inside double quotes, That variable is read. but considered as string as it is encapsulated with single quotes.
I have a few string variables I am trying to insert them into my DB but I am having trouble because nothing is being inserted into the DB. I know the variables are populated. Since all variables are string I'm converting some of them to integers because those fields in the db table are type integer. I tried assigning the mysql_query to a variable and then check to return an error but it didn't display anything. I'm a bit new at PHP so I'm not sure what's wrong with my code below. I appreciate the help.
$connect = mysql_connect("localhost", "user", "pass");
if (!$connect) { die("Could not connect: ". mysql_error()); }
mysql_select_db("dbname");
mysql_query($connect,"INSERT INTO table1 (id, AU, TI, JO, VL, ISS, PB, SN, UR, DO, SP, EP, PY) VALUES ('NULL', '".$authors."', '".$title."', '".$journal."', '".(int)$volume."', '".(int)$issue."', '".$publisher."', '".$serial."', '".$url."', '".$doi."', '".(int)$startpage."', '".(int)$endpage."', '".(int)$year."')");
mysql_close($connect);
Try to debug your code, adding some more useful checks.
$link = mysql_connect("localhost", "user", "pass");
if (!$link) {
die("Could not connect: ". mysql_error());
}
$dbSelected = mysql_select_db("dbname", $link);
if (!$dbSelected) {
die ("Can't select db: " . mysql_error());
}
$result = mysql_query("YOUR_QUERY", $link);
if (!$result) {
die("Invalid query: " . mysql_error());
}
ps: you may want to use mysqly::query, just because mysql_query is deprecated
ps2: you should google about SQL Injection, since your statement doesn't look secure (unless those values are escaped somewhere)
NOTE: I just noticed that you are using a wrong order for the parameters on mysql_query($query, $link). You have put $link as first parameter.
I create function for make query in database:
function mysqli($query){
$mysqli = new mysqli('test','test','test','test');
if (mysqli_connect_errno()) {
printf("Bad connect: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$mysqli->close();
return $result;
};
In next step I want get count affected rows.
For this I make:
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2->affected_rows;
But I get Notice: Trying to get property of non-object on line echo $res2->affected_rows;
How to get count of affected_rows?
This function is pointless and harmful.
And should never be used.
All other answer told you to remove most useless parts. While what you really have to remove is connection part. Which makes whole function useless.
And even harmful, as you will kill your MySQL server by connecting every time you are going to run a query.
And even more harmful as it doesn't support prepared statements.
Remove $mysqli->close(); And make use of
$mysqli->query("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $mysqli->affected_rows;
change
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
to
$res2 = mysqli_query("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
Remove the line:
$mysqli->close();
from the function. and this will work.
function mysqli($query){
$mysqli = new mysqli('test','test','test','test');
if (mysqli_connect_errno()) {
printf("Bad connect: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$arr = array($result,$mysqli);
return $arr;
}
Amd the use like this:
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2[1]->affected_rows;
And your result will be in this variable: res2[0];
Read this answer: mysqli_affected_rows() expects parameter 1 to be mysqli, object given
I'm trying to insert products information into the database, but I must be missing something. It does not insert anything into the database, it's not even showing any errors.
Whats wrong with my code?
<?php
if(!empty($product_name)){
if(!empty($product_category)){
////////////////////////////////////////////////
///// connect to database
////////////////////////////////////////////////
$dbc = new mysqli("localhost", "root", "password", "table");
// Check connection
if (mysqli_connect_errno($dbc)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['product_name'])) {
$pid = ($_POST['thisID']);
$product_name = ($_POST['product_name']);
$product_category = ($_POST['product_category']);
$product_detail = ($_POST['product_detail']);
$product_price = ($_POST['product_price']);
$product_company = ($_POST['product_company']);
$query = "INSERT INTO product (product_name, product_category, product_price, product_detail,product_detail, product_company)
VALUES ( '$product_name','$product_category','$product_price','$product_detail','$product_company')";
$result= $this->mysqli->query($query) or die(mysqli_connect_errno()."Data cannot inserted");
if($result){
header('location:cp_product.php');
}
mysqli_close($dbc);
}
}}
?>
In your query you have add the product_detail column two times,there should be one ,as five columns refers to 5 values
product_detail,product_detail,
INSERT INTO product (product_name, product_category, product_price, product_detail, product_company)
VALUES ( '$product_name','$product_category','$product_price','$product_detail','$product_company');
product_detail twice in insert query
This line is wrong:
$result= $this->mysqli->query($query) or die(mysqli_connect_errno()."Data cannot inserted");
It should be:
$result = $dbc->query($query) or die ($dbc->error . "Data cannot be inserted");
If you'd done this, you would have gotten the error that the column list doesn't match the VALUES list, because you put product_detail in the column list twice.
i see that you called your database "table".
Is your database called "table" ?
First Try this and tell us what errors your get:
Do not mix procdeural code with obejct oriented code. Check php.net examples.
(Remove all "ifs" for now.)
$dbc = new mysqli("localhost", "root", "password", "table");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pid = ($_POST['thisID']);
$product_name = ($_POST['product_name']);
$product_category = ($_POST['product_category']);
$product_detail = ($_POST['product_detail']);
$product_price = ($_POST['product_price']);
$product_company = ($_POST['product_company']);
$query = "INSERT INTO product (product_name, product_category, product_price, product_detail, product_company)
VALUES ( '$product_name','$product_category','$product_price','$product_detail','$product_company')";
echo "query: ".$query."<br>";
mysqli->query($query);
$mysqli->close(); //object oriented.
?>
You need your DB connection, in this case $dbc, inside of the HTML form variables you're setting.
$pid = ($dbc, $_POST['thisID']);
$product_name = ($dbc, $_POST['product_name']);
$product_category = ($dbc, $_POST['product_category']);
$product_detail = ($dbc, $_POST['product_detail']);
$product_price = ($dbc, $_POST['product_price']);
$product_company = ($dbc,$_POST['product_company']);
Nobody said that ! how do you pass your query through your connection ?
You should have something like
$dbc->query( $query )
Or in your case where do you assign $this->mysqli ?
Don't mix Object Oriented style with Procedural style as this may cause you confusion in the future.
Choose one and continue coding in that style. If you can choose OOP.
GOOD LUCK
.I don't know if it's syntax or what. I've tried a variety of ways this is the simplest I thought would work.
I send info to the userData.php using:
http://mydomain.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
On the userData.php I have:
<?php
$db = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db('databaseName', $db) or die('Could not select database');
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$name = mysql_real_escape_string($_GET['name']);
$date = date("d/m/Y");
$adClick = mysql_real_escape_string($_GET['adNum]);
$playN = mysql_real_escape_string($_GET['playClick']);
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
mysql_close($db);
?>
I manually added 2 records to the table from phpMyAdmin, and I can display or update them just fine but adding a new record isn't working. I simply want to start a new record each time the link is called from another program, and store the mac address, date, adNum, and playClick.
EDIT2:: echo $query; for
http://simplehotkey.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
outputs:
INSERT INTO playerData(mac,date,AdClick,PlayNum) VALUES ('001EC946C2F4', '26/07/2012','1','1')
Which is what I want it's just not adding it to the DB.
Correct syntax is --
mysql_select_db("databaseName", $db);
And its better if u use something like this for connection errors--
$db_selected= mysql_select_db("databaseName", $db);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
EDIT
You are writing all wrong :(
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) <--------------WRONG
Try Something like this----
$query = "INSERT INTO playerData(CORRECT_COL_NAMES) VALUES ('$name', '$date','$adClick','$playN')";
$results = mysql_query($query, $connection);
NEW EDIT
AREA OF ERROR---- WRONG DATATYPE
','1','1' <--- this is passing as string while u have have this as an int in your db structure ..now run the same query as it is to figure out the error..also u can figure out using $result = mysql_query($query) or die(mysql_error());
It's pretty easy to see what's wrong here, especially with syntax highlighting.
$adClick = mysql_real_escape_string($_GET['adNum]);
This line is missing a single quote mark; it should be:
$adClick = mysql_real_escape_string($_GET['adNum']);
This is a syntax error that ruins everything else.
Not to mention that your database selection is missing your database handler, ie:
mysql_select_db('databasename',$db);
As pointed out by #swapnesh, and as noted here.
Edit
I have been unable to reproduce your lack of an error, what I have gotten however, are errors. Firstly, you have an extra ) at line 12:
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should be:
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Lastly, you actually improperly execute your query twice, so the second time, the query is empty. What you have:
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should instead be:
$query = "INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Instead of using the insert statement the way you do add the fields that will receive entries explicitly. The database table might have more fields and the insert statement does not explcitly state which fields will receive data.
$query = mysql_query("INSERT INTO playerData (Name,Date,AdClick,PlayN) VALUES ('$name', '$date','$adClick','$playN')");
You have the syntax error on this line
Wrong :
$adClick = mysql_real_escape_string($_GET['adNum]);
Correct :
$adClick = mysql_real_escape_string($_GET['adNum']);