it's my first time working with php and after 2h of searching for my problem i came to the conclusion that i cant find and fix it.
I hope you guys can help me!
<?php
require "./config/_sqlconnect.php";
$temp = $_POST;
$vname = "Peter";
$nname = "Hans";
$straße ="XY";
$strnr ="8";
$plz = "9031";
$ort = "würzburg";
$land ="deutschland";
$tel ="1334134";
$email ="asdas#aasd.com";
$datum ="21.03.1942";
$anrede ="herr";
$connection = mysql_connect($dbhost, $dbuser, $dbpass, $dbname) or die
("Verbindungsversuch fehlgeschlagen");
mysql_select_db($dbname, $connection) or die('DB FAIL');
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES($temp)";
$eintrag = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES ('$vname','$nname','$straße','$strnr','$plz','$ort','$land','$tel','$email','$datum','$anrede')";
$eintragen = mysql_query($eintrag);
if($eintragen == true)
{
echo 'RICHTIG';
}
else
{
echo 'FEHLER';
}?>
the Result:
Notice: Array to string conversion in C:\xampp\htdocs\aufgabe\text.php on line 23
FEHLER
As the error suggest you are passing an array, but there is needed of a string. Your $temp is an array because it's the same as $_POST. So if you are sure that you want to pass there the $temp you have to change like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('" . implode("','", $temp) . "')";
But I see that you also have all the variables also so you can pass one by one here in VALUES like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('$vname', '$nname', '$straße', ....)";
And my suggestion is to use only English characters so to change $straße to something else
Related
I have made a form which contains two sets of checkboxes and would like to store them in a MySQL Database however when I post to the Database all the data comes through as intended such as the date, text and radio buttons except for the two textboxes. If I look into the database the columns where the value for the textboxes is stored it only says "Array" and none of the actual values.
This is my code that handles the post request:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['input4'];
$datedone = $_POST['date'];
$projectnumber = $_POST['input1'];
$area = $_POST['input2'];
$donebefore = $_POST['radio9'];
$changesmade = $_POST['radio8'];
$safeaccess = $_POST['radio11'];
$electrical = $_POST['radio5'];
$machineguarding = $_POST['radio6'];
$correctequipment = $_POST['radio4'];
$sds = $_POST['radio3'];
$controltoxic = $_POST['radio1'];
$ppe = $_POST['radio2'];
$hazard = $_POST['checkbox'];
$otherhazards = $_POST['input3'];
$controlofhazards = $_POST['checkbox1'];
$monitor = $_POST['radio12'];
$comments = $_POST['input'];
$sql = "INSERT INTO hira (Name, TodayDate, ProjectNumber, Area, DoneBefore, HaveChangesMade, SafeAccess, ElectricalEquipment, MachineGuarding, CorrectEquipment, SDS, ControlToxic, PPE, Hazard, OtherHazard, ControlHazard, MonitorProcess, AdditionalComments) VALUES ('$name','$datedone','$projectnumber','$area','$donebefore','$changesmade','$safeaccess','$electrical','$machineguarding','$correctequipment','$sds','$controltoxic','$ppe','$hazard','$otherhazards','$controlofhazards','$monitor','$comments')";
if ($conn->query($sql) === TRUE) {
echo "Thank you for completing the Hira form";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
What have I done wrong here. I would like the values of the textboxes stored comma separated i.e. "Noise, Dust"
Is this possible?
Thanks in advance
you can use implode function
$checkbox = implode(",",$_POST['checkbox']);
you can use the implode function for insert array using , seperated string
$values = implode(",",$_POST['name']);
you can use the explode function to retrieve the string to array
$values = explode(",",$values);
my mysql table accepts NULL values on many fields, I'm updating records and my desktop app is creating a http string as follows and sending to a php script.
www.webpage/script.php?firstval=48.345345&secondval=234&thirdval=&fourthval=simon
on the db thirdval is already NULL
but the parameters in the http string may or may not hold values
do I need to :
A)pass the parameter in the http string as
b)pass the parameter in the httpstring as
c)cater for the null value in the php script(
d)not include the parameter in the http string at all
or something else
my phpscript is like so :
?php
DEFINE ('DBUSER', 'generic01');
DEFINE ('DBPW', 'genpass');
DEFINE ('DBHOST', 'mysql4.xxxxxxxxx.com');
DEFINE ('DBNAME', '_Places');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die(" Database selection bit failed: " . mysqli_error($dbc));
exit();
}
$lat = mysqli_real_escape_string($dbc, $_GET['lat']);
$lng = mysqli_real_escape_string($dbc,$_GET['lng']);
$prox = mysqli_real_escape_string($dbc,$_GET['prox']);
$description = mysqli_real_escape_string($dbc,$_GET['description']);
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$direction = mysqli_real_escape_string($dbc,$_GET['direction']);
$avoiddays = mysqli_real_escape_string($dbc,$_GET['avoiddays']);
$validfrom = mysqli_real_escape_string($dbc,$_GET['validfrom']);
$validto = mysqli_real_escape_string($dbc,$_GET['validto']);
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
$expiry = mysqli_real_escape_string($dbc,$_GET['expiry']);
$query = "UPDATE places SET rt_lat = '$lat',rt_lng= '$lng',rt_prox = '$prox', rt_description = '$description', rt_direction = '$direction',rt_avoiddays = '$avoiddays',rt_validto = '$validto',rt_validfrom = '$validfrom',rt_gefid = '$gefid',rt_expiry='$expiry' WHERE rt_id = '$id'";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
All help appreciated,
You do not need to include it in the http request, but you have to catch that, otherwise you get an E_NOTICE error.
For all fields that can be null:
if (isset($_GET['gefid'])) {
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
} else {
$gefid = null;
}
PHP has no knowledge of SQL nulls. If you want a blank/not-set $_GET value to become a null in the DB, then you have to take special steps:
if(isset($_GET['lat']) || ($_GET['lat'] == '')) {
$lat = 'NULL'; // a plain PHP string with the word "null" in it
} else {
$lat = "'" . mysqli_real_escape_string($dbc, $_GET['lat']) . "'"; // note the extra quotes
}
$sql = "INSERT ... VALUES ($lat, ....)"
If you do it any other way, e.g (just as an example, yes it's sql-injection vulnerable):
$sql = "INSERT ... VALUES ('$_GET[lat]', ...)";
Then for an empty $_GET['lat'] your query would actually be
INSERT ... VALUES ('', ...)
and you'd be inserting an empty string, NOT an sql null.
I'm trying to insert some data into a mysql table but the process doesnt go through and I get nothing printed for the error. I don't think I'm outputting the errors correctly. Looking at php.net it seems like I'm doing the error handling properly but maybe I'm missing something.
Here is the code
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sqlInsert = $db->query("INSERT INTO transactions(`user_id`, `courses`, `invoice`, `start_date`, `end_date`, `mc_gross`, `email`) VALUES ('".$user_id."','".$trim."','".$invoice."','".$start_date."','".$end_date."', '".$email."')");
if($sqlInsert)
{
echo "Inserted successfully";
}
else
{
printf("Error: ", $db->error);
}
The values for the variables are as follows
$custom = $_SESSION['custom'];
$user_id = $_POST['userID'];
$pwd = $_POST['password'];
$email = $_POST['email'];
$start_date = date('Y-m-d');
$end_date = date (('Y-m-d'), strtotime('+120 days'));
$invoice = date('Ymd'). mt_rand(1252,10000);
$invoice_check = $db->query("SELECT `invoice` FROM `transactions` WHERE `invoice` = $invoice");
while ($rows = $invoice_check->fetch_assoc())
{
$invoice = date('Ymd'). mt_rand(1252,10000);
}
$mc_gross = $_SESSION['subtotal'];
$trim = rtrim($custom, ",");
the var_dump for $trim is string(17) "bio_01,calculus_01" and the other variables just echo out normally as you'd expect.
Any ideas?
EDIT Updated the code with $db instead of $sqlInsert. Still no output for an error.
Change:
printf("Error: ", $sqlInsert->error);
to:
printf("Error: %s", $db->error);
You can't read the error property of false, because it's not an object. And you're missing the %s in the printf format string to substitute the argument.
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I am getting an error and for the life of my can't figure it out. My code is kind of messy so watch out:
$hostname = ""; //SET SERVER/HOSTNAME
$dbusername = ""; //SET DATABASE USERNAME
$dbname = ""; //SET DATABASE NAME
$dbpassword = ""; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "SELECT * FROM utility WHERE `program_code` = '$program_code'";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!$result)
{
echo 'Error: ', $mysqli->error;
}
while($row = $result->fetch_assoc()){
$program_code1 = $row['program_code'];
$utility_company = $row['utility_company'];
$rate = $row['rate'];
$term = $row['term'];
}
$sql1 = "INSERT INTO v88374 (id, ldc_account_num, revenue_class_desc, first_name, last_name, home_phone_num, sline1_addr, scity_name, spostal_code, marketer_name, distributor_name, service_type_desc, bill_method, enroll_type_desc, requested_start_date, plan_desc, contract_start_date, contract_end_date, fixed_commodity_amt, vendor_id, office_id, agent_id, customer_name, contact_name, result, promo_code, validation_code, email, state, bname, baddress, program_code, date) VALUES ( '','$ldc_account_num1','$revenue_class_desc','$first_name1','$last_name1', '$home_phone_num1','$sline1_addr1','$scity_name1','$spostal_code1','','$utility_company','$service_type_desc','$bill_method','$enroll_type_desc','$requested_start_date','$plan_desc','$contract_start_date','$contract_end_date','$rate','$vendor_id','$office_id','$agent_id1','$customer_name','$contact_name','$result','$promo_code','$validation_code1','$email1','$state1','$bname1','$baddress1','$program_code1', now())";
$result1 = mysqli_query($link, $sql1, MYSQLI_STORE_RESULT);
if (!$result1)
{
echo 'Error: ', $mysqli->error;
}
else if ($result1){
echo "Thank you. Information submitted.";
}
I am getting the error (in the subject of this question)when my second sql statement starts, at $sql1 = long_string_of_code
I'm thinking it's something with my variables from the first statement maybe? If I echo my variables from the first statemenet, I get them all ok. So I am not sure what the deal is. Any help is appreciated, I know this is a lot of code to go through. Thank you.
contact_name','$result','$promo_code'
Your using result in the second SQL. Its an object so you can't use it as a string. Change that variable and it should work
In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))