Multiple Results being uploaded to table - php

I've been struggling with trying to add the same variable into two of the tables I have on my database and so have decided to work around it and use two separate insert statements instead
if ($cuisinetype !='empty'){
$query="SELECT cuisine_type FROM `Nation` WHERE cuisine_type='$cuisine'";
$result=mysqli_query($db_server, $query) ;
if ($row = mysqli_fetch_array($result)){
$message = "Sorry we already have that one!";
}else{
$query = "INSERT INTO`Nation`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
$query2 = "INSERT INTO`recipename`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
}
}
This is how my sql statement looks right now, but now it's putting two variables into my Nation table and still nothing into the recipename table
Still relatively new to all things PHP/MySQL and considering beforehand it was working am very confused.

try this under your second insert:
mysqli_query($db_server, $query2) or ... Replace the $query with $query2

Related

How to insert data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one insert in table "TabelaX" which is in another database. I already made some code but it is not working correctly. And this error appears:
"Error: INSERT INTO TabelaX (ID, Nome, Dados) VALUES (2000, XPTO2,
12345); Unknown column 'XPTO2' in 'field list'Error: INSERT INTO
TabelaX (ID, Nome, Dados) VALUES (2033, XPTO3, 1234567890); Unknown
column 'XPTO3' in 'field list'"
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Nome"];
$row3 = $row["Dados"];
mysqli_select_db($conn,"Servidor1");
$sql = "INSERT INTO TabelaX (ID, Nome, Dados)
VALUES ($row1, $row2, $row3);";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
From what I have read, your current approach might be the only way to do this using regular queries with MySQL. But, if you were doing this directly on MySQL, you could just use a simple INSERT INTO ... SELECT:
INSERT INTO db1.TabelaX (ID, Nome, Dados)
SELECT ID, Nome, Dados
FROM db2.TabelaY;
One possibility would be to create a stored procedure on MySQL which does the above insert, and then call it from your PHP code:
$result = mysqli_query($conn,
"CALL YourProcName") or die("Query fail: " . mysqli_error());

PHP MySQL inserting information from one form into multiple tables

So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}

If text box is empty choose option and insert to table

I am working on a recipe website one of the fields on the recipe upload page gives the user the option to either upload a value via a dropdown menu or add a new one via a text box
I have made it work so when the dropdown has no value it will choose the text however this does not work the other way round I'm getting this error:
Insert failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '30'>English
Here is the insert code:
if($cuisine==""){
$query="INSERT INTO`recipename`(cuisine_type)VALUES('$cuisinetype')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
}
//check whether the cuisine type exists//
if ($cuisinetype !='empty'){
$query="SELECT cuisine_type FROM `Nation` WHERE cuisine_type='$cuisine'";
$result=mysqli_query($db_server, $query) ;
if ($row = mysqli_fetch_array($result)){
$message = "Sorry we already have that one!";
}else{
$query = "INSERT INTO`Nation`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) ;
}
}
$query = "INSERT INTO `Nation` (cuisine_type) VALUES ('$cuisine')";
Add spaces!
Anyway, please, take a look at this to prevent SQL Injections, just in case you've missed it.

PHP MYSQL Couldn't execute query: Unknown column

Please help me to figure out this. The first query would return a message saying that
Couldn't execute query: Unknown column 'ssd23' in 'where clause.
ssd23 is the value the $_POST will get for the pnumber from a html form. However, it would work if there are only digits.
$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = {'$_POST['pnumber']'}") or die ("Couldn't execute query: " .mysqli_error($con));
This second query below would work with both digits and characters after using a variable.
$test = $_POST['pnumber'];
$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = '$test'") or die ("Couldn't execute query: " .mysqli_error($con));
replace this:
$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = {'$_POST['pnumber']'}") or die ("Couldn't execute query: " .mysqli_error($con));
With this:
$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = '" . $_POST['pnumber'] ."'") or die ("Couldn't execute query: " .mysqli_error($con));
Notice I did not take care of sql injection above
Even better is to use prepare statements that will secure your querys, in your case it will be something like this:
$sql= 'DELETE FROM Tools WHERE PartNumber= ?';
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $_POST['pnumber']);
$stmt->execute();

php insert mysql not working

.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']);

Categories