PHP ~ Column count doesn't match value count at row 1 - php

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();

Related

How do I echo name, price and id from a form just submitted?

I have an issue with MySQLi and PHP.
I created a form, and once I type the desired values in and hit submit, the values are right away sent to the database. Nothing wrong with this.
What I want to happen is that: after hitting the submit button, PHP shall echo the result of the just-submitted entry. That is to say:
`INSERT INTO table VALUES (x, x, y) -> SELECT x, x, y FROM table ORDER BY id DESC LIMIT 1`
I have tried many methods to do this, but all of them either echo the previous entry (the one before the one just submitted) or plainly don't work.
I have tried mysqli_insert_id($conn) but this returns nothing.
This is where my code rests at at the moment:
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$nome = $_POST['nome'];
$preco = $_POST['preco'];
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$result = mysqli_insert_id($conn);
var_dump ($result);
if (mysqli_query($conn, $query)){
echo '<br>'."Succeeded!";
} else {
echo '<br>'."ERROR!" .'<br>'. $query ."<br>". mysqli_error($conn) .'<br><br>'. '<span style="color: #FF0000;">You have to fill all the fields.</span>';
}
mysqli_close($conn);
to note, if of any help, var_dump outputs int(0) at the moment.
Thanks in advance. I've been struggling like mad with this.
You can't get mysqli_insert_id without executing the query. Better use prepare statement to prevent from sql injection
$stmt = $conn->prepare("INSERT INTO produtos(nome, preco) VALUES (?,?)");
$stmt->bind_param('ss', $nome, $preco);
$stmt->execute();// execute query
$conn->insert_id;// get last insert id
Please see that you haven't even executed your query. On a side note, you should be aware of SQL injections and follow the below pattern:
$nome = mysqli_real_escape_string($conn, $_POST['nome']);
$preco = mysqli_real_escape_string($conn, $_POST['preco']);
$sql = "INSERT INTO produtos (nome, preco) VALUES ('".$nome."', '".$preco."')";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result = mysqli_insert_id($conn);
echo $result; // Check your result.
Use this:
$query = "INSERT INTO produtos(nome, preco) VALUES ('$nome', '$preco')";
$res=mysqli_query($conn,$query);
$result = mysqli_insert_id($conn);
var_dump ($result);`

selecting mysql database's table in php $query

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.

PHP inserting data from one table to another

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

Inserting data in 2 table on the same form [duplicate]

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();
?>

Creating an "update" page MYSQL/PHP

I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.

Categories