I am sending from arduino usinh http 1.1 (x-www-form-urlencoded) temperature and humidity readings to mysql database. if I use commented part of the following code, everything works (tab12 is the name of the table in mysql database). But I would like to arduino send the name of the table, so I could use the same add.php file to play with multiple arduinos. The thing is, I don't understand how to correctly put the table name from $tabid=$_POST["tabid"]; to query.
<?php
include("connect.php");
$link=Connection();
$tabid=$_POST["tabid"];
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
// $query = "INSERT INTO `tab12` (`temperature`, `humidity`)
// VALUES ('".$temp1."','".$hum1."')";
$query = "INSERT INTO `"tabid"` (`temperature`, `humidity`)
VALUES ('".$tabid."','".$temp1."','".$hum1."')";
mysql_query($query,$link);
mysql_close($link);
header("Location: index.php");
?>
You would concatenate just as you would with any variable:
$query = "INSERT INTO `" . $tabid . "` (`temperature`, `humidity`)
VALUES ('".$temp1."','".$hum1."')";
In addition your number of columns and values must match.
Related
Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();
<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
// echo $row['Name']. " - ". $row['email'];
// echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>
i have the above code i am trying to insert data from one table to another
The above code do not returning any error but it do not puts any data to second table "other_user"
There is an error in INSERT query - you have to enclose strings in quotes, like this:
"INSERT INTO other_user (user_id, username, email)
VALUES ($userid, '$username', '$email')"
A single query would be enough:
$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
SELECT id, Name, email FROM users WHERE status='ACTIVE'");
No need for an agonizing slow row by row insert.
PS: The original error was leaving out quotes around your values.
You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection
I think you should carefully check the table design of your new table.
Check if the column names and types are what you expect.
Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.
PHP won't let me insert my username field into the database for some reason:
$username = "<a href='user.php?user=".$_SESSION['username']."'>#".$_SESSION['username']."<a>";
/* Query database to save user's post */
/* If field "repostid==0", then the post is not a repost; if the field "repostid>0", then the post is a repost with the field "repostid" linking to the id of the post to be reposted */
$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('$username', '$final_repostinfo', '$_GET[postid]', '$date_string')");
if (!$result)
{
die('Cannot query. Error: ' . mysqli_error($connection));
}
The returned PHP syntax error:
Cannot query. Error: 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 'user.php?user=shawn619'>#shawn619', 'fifth', '8', '01/12/2013 21:38:56')' at line 1
You can solve it by separating the html markup.
I had a similar problem when trying to insert html markup into a database.
Leave $username as being just $_SESSION['username'], then when you need to retrieve the value from the database THAT'S when you add the html markup.
For example, I was trying to cut corners by having the markup entered into the database, rather than putting it where it needs to be used.
I had the following PHP code:
$image = "<img src='".$_FILES['image']['name']."' />";
$query = mysql_query("INSERT INTO news VALUES (CURRENT_DATE,'$image')");
Then in the page I was using to retrieve data from the database:
echo $row['images'];
I discovered that what I SHOULD be doing is PHP code:
$image = $_FILES['image']['name'];
$query = mysql_query("INSERT INTO news VALUES (CURRENT_DATE,'$image')");
and put the markup in its proper place:
echo "<img src='";
echo $row['images'];
echo "' />";
I think you can implement a similar strategy to your code to fix the problem.
NOTE: mySQL is now depreciated, but you can use this technique with it's successors, mySQLi and PDO.
It's because of the single quotes. Try:
$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('".mysql_real_escape_string($username)."', '$final_repostinfo', '$_GET[postid]', '$date_string')");
Or
$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('".add_slashes($username)."', '$final_repostinfo', '$_GET[postid]', '$date_string')");
Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?
You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}
Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
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')";