Adding data to MySQL won't work - mysql

Can't figure out what I'm doing wrong here:
<?php
include "dbopen.php";
$fnamn = $_POST["fnamn"];
$enamn = $_POST["enamn"];
$email = $_POST["email"];
mysqli_query($dbconnect,"INSERT INTO personer (Fornamn, Efternamn, Email) VALUES ($fnamn, $enamn, $email)");
?>
The include tag works fine, since I can create data in phpmyadmin and get it to write out the data, but adding won't work. Ain't getting any errormessages either...
Thanks in advance!

Put quotes around these string values like
VALUES ('$fnamn', '$enamn', '$email')
And at the very minimum, run your POST values through mysqli_real_escape_string

<?php
include "dbopen.php";
$fnamn = mysqli_real_escape_string($dbconnect, $_POST["fnamn"]);
$enamn = mysqli_real_escape_string($dbconnect, $_POST["enamn"]);
$email = mysqli_real_escape_string($dbconnect, $_POST["email"]);
$sql = "INSERT INTO `personer` (`Fornamn`, `Efternamn`, `Email`) VALUES ('".$fnamn."', '".$enamn."', '".$email."');";
if (mysqli_query($dbconnect, $sql) === true) {
printf('Success');
} else {
print_f(mysqli_error($dbconnect));
}
?>

Related

Cannot push data to mysql

I can't seem to push data from my form to the database, I have checked the error_log and there's no error. Please check my codes below, thank you!
<?php
$con=mysqli_connect("localhost","admineventus","J7!ren;3") or Die ("Cannot connect");
mysqli_select_db($con,"eventus");
if(isset($_POST['submitpublish']))
{
mysqli_query($con,"insert into events values('$_POST[Category]','$_POST[Name]','$_POST[Location]','$_POST[Sdate]','$_POST[Edate]','$_POST[Etime]','$_POST[Fee]','$_POST[Free]','$_POST[About]')");
}
?>
Try this
if(isset($_POST['submitpublish']))
{
$sql = "INSERT INTO events (col1, col1, .. , colx)
VALUES ('".$_POST["Category"]."','".$_POST["Name"]."','".$_POST["Location"]."','".$_POST["Sdate"]."','".$_POST["Sdate"]."','".$_POST["Edate"]."','".$_POST["Etime"]."','".$_POST["Fee"]."','".$_POST["Free"]."','".$_POST["About"]."')";
$result = mysqli_query($conn,$sql);
}
Make sure your code enters in IF statement

my INSERT query not working

i dont know why but these values are not going into my database.these is my code.
<?php
define('INCLUDE_CHECK',true);
require '../database/connect.php';
session_name('user');
session_set_cookie_params(2*7*24*60*60);
session_start();
if(isset($_POST['submit']) && $_POST['submit']=='Submit')
{
$stdID='CC13051';
$itemCODE='00';
$pckgeID='1';
$condition='qwe';
$duration='5';
$status='Not Approved';
mysqli_query($link," INSERT INTO storage_details(stdID,itemCODE,pckgeID,cndition,duration,status)
VALUES(
'$stdID',
'$itemCODE',
'$pckgeID',
'$condition',
'$duration',
'$status',
)");
if (mysql_errno()) {
die('Invalid query: ' . mysql_error());
}
}
?>
mysql_err didnt give out anything.or am i using it in the wrong way?
mysqli_query($link," INSERT INTO storage_details(stdID,itemCODE,pckgeID,cndition,duration,status)
VALUES(".$stdID.",".$itemCODE
You are including you PHP variables in SQL as strings, change to include as PHP variables and concatenate them into SQL using .
Seems like you are not connecting to database.
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbName");
?>
Try to replace
if(isset($_POST['submit']) && $_POST['submit']=='Submit')
By
if(isset($_POST['submit']))
i forgot to remove the comma after $status. thanks to #Tobias Baumeister for pointing it out.
mysqli_query($link," INSERT INTO storage_details(stdID,itemCODE,pckgeID,cndition,duration,status)
VALUES(
'$stdID',
'$itemCODE',
'$pckgeID',
'$condition',
'$duration',
'$status', <-- this comma should not be here
)");

INSERT INTO MYSQL - Can´t insert data

After a couple of week´s trying to insert data in variables from form in MYSQL database, i´m asking here. I found a lot of example codes of INSERT INTO and also my provider checked my skript. He said I have a problem in my $sql=.
I tryed a lot of, but i can´t see any data in phpMyAdmin after click submit, but i receive the mail, that works fine.
Maybe anybody can see an issue in my script.
<?php
if(isset($_POST["sendcopy"])){
mail($mailToCC, $subject, $textCC, $from);
}
if(isset($_POST["submit"])){
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO "offen"("id", "vorname", "nachname", "email", "telefon", "geburtsjahr", "postleitzahl", "datum", "stunde", "minute", "personen", "bereich", "nachricht")
VALUES ($id, $vorname, $nachname, $email, $tel, $geburtsjahr, $plz, $datum, $stunde, $minute, $personen, $bereich, $nachricht)';
mysql_close($connect);
}
include ("reservtrue.php");
exit;
?>
The "submit" comes from a <form> below.
<form method="post" action="mailer.php" onsubmit="return chkFormular()" name="Formular" id="formTemplate">
<table id="reservtable">
.
.
.
.
<input type="submit" name="submit" value="Reservieren" id="submit">
</td>
</tr>
</table>
</form>
I hope it´s no problem to use german words as variables, here in stackoverflow.
Thank´s for help.
EDIT
Thank you for you´r suggestions. I still can´t insert data from form to MYSQL. I changed my Code a bit. And if I paste the code into phpMyAdmin - SQL, it work´s! But not if I load my script to server and test my form in web.
This is my new Code:
<?php
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST["submit"])){
$vorname = $_POST["Vorname"];
$nachname = $_POST["Nachname"];
$email = $_POST["Mailadresse"];
$tel = $_POST["Telefonnummer"];
$geburtsjahr = $_POST["Geburtsjahr"];
$plz = $_POST["PLZ"];
$datum = $_POST["Datum"];
$stunde = $_POST["Stunde"];
$minute = $_POST["Minute"];
$personen = $_POST["Personen"];
$bereich = $_POST["Bereich"];
$nachricht = $_POST["Nachricht"];
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$insert = ("INSERT INTO offen(vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('".$id."', '".$vorname."', '".$nachname."', '".$email."', '".$tel."', '".$geburtsjahr."', '".$plz."', '".$datum."', '".$stunde."', '".$minute."', '".$personen."', '".$bereich2."', '".$nachricht."')");
mysqli_query($insert, $sql);
}
include ("reservtrue.php");
exit;
?>
Problem solved
Problem is solved with following code:
$insert = "INSERT INTO `offene`
(
`id`, `vorname`, `nachname`, `email`, `telefon`, `geburtsjahr`, `postleitzahl`, `datum`, `stunde`, `minute`, `personen`, `bereich`, `nachricht`
)
VALUES
(
NULL, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht');";
mysqli_query($connect, $insert);
Thank you guy´s for information, inspriation and tips! I learnd a lot in the last 2 days.
Where is your mysql_query($sql); ? Add this after your $sql. Your $sql query require mysql_query to run it. If you added that and it still doesn't work, I suggest your go to phpmyadmin's sql tab. Paste your query in with some random VALUES. That's how I check if my query is working or not.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO offen (id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('$id', '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')';
mysqli_query($connect,$sql); //this line was missing from your code.
mysqli_close($connect); //updated to make it MySQLi
The mysqli_query($connect,$sql) actually does the work of applying the SQL you define in the $sql query.
NOTE
You have both MySQLi and MySQL functions in your script, you must stick with just one function, ALL your SQL functions must be MySQL i .
I would recommend that you change your SQL query to use single quotes and backticks. The table name offen and the column names do not need to be in quotes. The variables you insert do need to be in quotes, as I have illustrated.
You do not (usually) need to have mysqli_close because the SQL connection automatically closes once the PHP reaches the end of the page.
The variable names don't need quotes but the parametes do. Also you are missing the code to execute the SQL statement.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= "INSERT INTO offen(id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ($id, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
mysql_close($connect);
}
It appears you have some understandable confusion about quoting of the variables in $insert. You likely have a problem with how you are handling your datatypes.
Here are a few things to look out for
You have too many quotes around your variables. Wrap the query in "" but save the '' for individual variables (where necessary, seen below). For instance, just wrap the variable once like so: .'$vorname'.' if the variable you are inputting is a string. If it is an integer (INT variable type), leave the quotes off, e.g.$number`. In other words, input strings as strings, and INT as int.
If the variable you wish to input is set as auto-increment in your database (i.e. it is the primary key), you probably don't want to be inputting it at all. For example, in your case $id appears to be one. If this is true, you have the syntax backward. Just input it as NULL or leave it off the insert, like so: insert into tablename (id, vorname) values (NULL, '$vorname')
You need to also sanitize your ALL of your variables if you to prevent SQL Injection (very possible with your code). You can do this with mysqli_real_escape_string()
OR instead of going through all of that, you could use prepared statements, which would both handle that information in a cleaner way, but also would protect your code against SQL injection.
Here's how to do this using mysqli:
Connect as an object:
$connect = new mysqli($host_name, $user_name, $password, $database);
And then feed your query into the object and bind the parameters. In this section, "s" is a string, "i" is an integer.
$insert = $connect->prepare("INSERT INTO offen(id, vorname, nachname, email)
VALUES (NULL, ?,?,?");
$insert->bind_param("sss", $vorname, $nachname, $email);
$insert->execute();
$insert->close();
If you name your variables correctly, this should work.

Can't get form posts to be stored in the database

I can't figure out why the posts from my form won't save in the database.
This is the html:
<button type="button" class="write">Write Reviews</button>
<form class="writeForm"method="post">
<input type="text" required name="monicker" placeholder="Name">
<textarea name="review" required maxlength="5000" placeholder="Leave your review here (max 25,000 charachters)"></textarea>
<input type="submit" value="Submit">
</form>
And the php:
<?php
$dbc = mysqli::real_connect('localhost', 'user_name', 'not_password');
mysqli::select_db('db_name',$dbc);
$monicker = mysqli::real_escape_string ($_POST['monicker']);
$review = mysqli::real_escape_string ($_POST['review']);
if(isset($_POST['Submit'])) {
$query = "INSERT INTO reviews
(id, monicker, review, date)
VALUES (DEFAULT,'$monicker', '$review', 'CURDATE()');";
mysqlI::query($dbc, $query);
}
mysqlI::close();
?>
As #maku said, you need to execute the query. But there is also more to it.
You have added $mysql_query, this is incorrect.
It is the wrong API (mysql vs. mysqli).
You also need to include your db connection.
If your id column is auto_increment, there is no need to insert it. Happens automatically.
There is no reason to assign a variable to the query because you are not selecting anything.
I would recommend using prepared statements instead, then you don't need to use mysqli::real_escape_string.
if(isset($_POST['submit'])) {
$query = "INSERT INTO reviews (id, monicker, review, date)
VALUES (DEFAULT,'$monicker', '$review', 'CURDATE()')";
mysqli_query($dbc, $query) or die(mysqli_error($dbc);
}
mysqli::close();
You didnt execute your query :
Add this line.
$result = $mysqli::query($query);
I modified your code, please check this code :
<?php
$dbc = mysql_connect('localhost', 'communi3_root', 'typeset');
mysql_select_db('communi3_cfds',$dbc);
$monicker = isset($_POST['monicker']) ? mysql_real_escape_string ($_POST['monicker']) : '';
$review = isset($_POST['review']) ? mysql_real_escape_string ($_POST['review']) : '';
if(isset($_POST['submit'])){
$current_date = date('Y-m-d H:i:s');
$query = "INSERT INTO reviews (id, monicker, review, date) VALUES (DEFAULT,'$monicker', '$review', '$current_date');";
$result = mysql_query($query)or die(mysql_error($dbc));
}
mysql_close();
?>
I found an issues in your previous code :
1. No checking on your POST variables. It causes error because you used it directly without checking if it is set or not.
2. CURDATE() is an undefined function, use PHP date function instead.

Why am I getting error SQLSTATE[HY093]: Invalid parameter number: ? How can I fix it?

Based on this question How to insert array into mysql using PDO and bindParam?
I'm trying to insert values of an array into mysql via PDO.
I'm having a hard time of it, because I keep getting the following error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
for this line $stmt->execute();
I'm guessing the problem has something to do with this line
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR); Specifically 'val$count', but I'm not sure exactly what is going wrong.
QUESTION: What am I doing wrong? How can I fix this?
Anyway here is the code I'm using along with the sample array.
$lastInsertValue=87;
$qid[0][0]=1;
$qid[0][1]=1;
$qid[1][0]=2;
$qid[1][1]="null";
$qid[2][0]=3;
$qid[2][1]=0;
$array_count = count($qid);
if (isset($lastInsertValue))
{
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
$a=0;
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2)";
$count = 0;
$stmt = $dbh->prepare($sql);
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
$stmt->execute();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Yikes, so many issues.
Your array building is so verbose. Try this
$stqid = array();
foreach ($qid as $qidArr) {
$stqid[] = $lastInsertValue; // no idea why you repeat this
$stqid[] = $qidArr[0];
$stqid[] = $qidArr[1];
}
Use positional placeholders if you're simply relying on number of arguments
$sql = 'INSERT INTO ... VALUES (?, ?, ?)';
bindParam uses references which you are overwriting with each loop iteration. You would want to use bindValue() instead
Your query only has 3 placeholders but your $stqid array has 9 items. This is the source of your error.
You have single quotes around a variable, which will be treated as the variable name $count (not the value), try concatenating the variable to the string. Give this a try:
$stmt->bindParam(':val' . $count, $val,PDO::PARAM_STR);
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
so in case $i = 2, it will add $stqid[6], $stqid[7], $stqid[8] so
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
will give you :val0 to :val8
In your query you have only :val0 to :val2.
Also having multiple values in one field in database is bad. Don't do it. Try to redesign your DB differently
EDIT: bad math in the morning... sorry