I have a problem with SQL syntax. I have 2 tables and the third table is generated in SQL Workbench (n:m relationship).
My 3rd table has 2 columns product_id and categories_id.
I use this SQL in php my admin to add a new row:
INSERT INTO `products_has_categories` (`products_id`, `categories_id`)
VALUES ('17', '1');
if phpmyadmin, the sql add a new row, with product_id = 17 and categories_id =1.
My problem:
i have a simple php file called test.php looking like:
$connection = mysqli_connect("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
}
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1');";
or
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')";
When i run test.php file, the code not working, and no adding new row in SQL table.
Can u help me?
As far I'm concerned, you're not even calling query().
Try this:
$connection = new mysqli("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
} else {
$query = $connection->query("INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')");
}
Related
When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.
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);
I have a web application in which students are divided into "batches".
I am trying to insert student for particular batch and the batch will be chosen by user by select option. After that student is added to the particular batch, he/she will be added to stdhold table. However, it is only inserting for the first selected value of select option.
<?php
function specialCOn() {
$connew = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connew,'mcqs');
return($connew);
}
if (isset($_POST['add']))
{
$namestd=$_POST['std_name'];
$batchstd=$_POST['batch'];
$FNAME=$_POST['f_name'];
$query3 = "INSERT INTO `$batchstd` VALUES('','$namestd','$FNAME')";
$rsq3 = mysqli_query(specialCOn(),$query3);
mysqli_close(specialCOn());
$queryrollno = "select rollno from `$batchstd` order by rollno desc";
$rsqrollno = mysqli_query(specialCOn(),$querrollno);
$getrollno = mysqli_fetch_array($rsqrollno);
$rollnoto = $getrollno[0];
echo "<script>alert('$batchstd')</script>";
echo "<script>alert('$rollnoto')</script>";
mysqli_close(specialCOn());
//Problem is here
$querystdhold = "INSERT INTO stdhold VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd')";
$rsqhold = mysqli_query(specialCOn(),$querystdhold);
mysqli_close(specialCOn());
if ($rsq3&&$rsqhold)
{
echo "<script> alert('Student Added.');
window.location.assign('addstudent.php');
</script>";
//header('Location:addstudent.php');
}
else
{
echo "<script> alert('You Havenot added Student.');
window.location.assign('addstudent.php');</script>";
}
}
?>
Try use this :
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO ? (col1,col2,col3) VALUES('',?,?)");
$stmt->bind_param('sss', $_POST['batch'], $_POST['std_name'], $_POST['f_name']);
$stmt->execute();
For the detail example you need to read the #Amber Answer how to create secured prepared statement.
Hope this'll help you.
Try specifying the column names in your insert query:
INSERT INTO stdhold (col1, col2, col3, col4) VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd');
For reference see the MySQL Insert documentation.
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')";
I have a simple script which I have included here. the select query works fine but the insert query fails. I am running php, apache and mysql on my macbook.
The table city_profile has ID as a auto increment primary key. And name is a non-null.
function testMySQL() {
$db = new mysqli('localhost', 'root', NULL, 'citee');
//$query = "select * from city_profile"; //this query works
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
//whereas the above one fails..
$results = $db->query($query);
if($results) {
echo '<p>The query is successful.</p>';
}else {
echo '<p>The query is NOT successful.</p>';
}
//close the connection
$db->close();
}
try to change this line:
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
into this:
$query = "insert into `city_profile` (`name`,`state`,`country`) values ('charlotte','north carolina','usa')";