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);
Related
I have an array $alert_note. I iterate through a loop and fill it up with a few strings:
$n = 0;
$alert_note = array();
$results = array();
while($row = mysqli_fetch_assoc($query)){
//some code in here populates the $results[$n] array with results from $row
$thisnote = "<b>Location alert</b><br>
Alert ID: {$results[$n]['alert-id']}<br>
Start: {$results[$n]['start-formatted']}<br>
End: {$results[$n]['end-formatted']}<br>
Radius: {$results[$n]['radius-km']} km<br>
Distance: {$results[$n]['distance-km']} km<br>
<ul>\n";
//$results[$n]['data'] is a nested array, so iterate through it:
foreach($results[$n]['data'] as $name => $data){
$thisnote .= "<li>$name: $data</li>\n";
}
$thisnote .= "</ul>";
$alert_note[$n] = $thisnote;
$n++;
}
Then I call a foreach function:
foreach($alert_note as $alert_note_contents){
error_log("Note: $alert_note_contents");
mysqli_query($dblink, "INSERT INTO `incident_events` (`incident`, `data`, `time`, `operator`) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')");
}
Each string in $alert_note shows up as expected in the PHP error log, but only the last one is inserted into the MySQL table. No PHP errors are being thrown. Any ideas why this may be?
plz before foreach($alert_note as $alert_note_contents){
do this so i can get the error
var_dump($alert_note );
and do this plz so i can see if there is any error ind db
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{ die("Connection failed: " . $conn->connect_error); }
$sql = "INSERT INTO incident_events (incident, data, time, operator) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')";
if ($conn->query($sql) === TRUE)
{ echo "New record created successfully"; }
else { echo "Error: " . $sql . "<br>" . $conn->error; }
$conn->close();
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
So, everytime I go to http://localhost/api/calls.php?gamename=test&gameowner=hi&gameownerid=1&placeid=2&serverjobid=hi&serverid=jaja&serverplayers=1&sendername=bob&senderid=3&senderage=14&senderwarnings=0&calltype=non&reportinfo=hi&suspect=none
it shows absolutely nothing and doesn't send the data to my mysql database.
Here is my code. I removed my mysql info just to be safe.
<?php
$servername = "";
$username = "";
$password = "";
$database = "";
// Establish MySQL Connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("MySafeServer Database Connection Failed: " . $conn->connect_error);
}
if (array_key_exists('param',$_GET)) {
$gamename = $_GET['param'];
$gameowner = $_GET['param'];
$gameownerid = $_GET['param'];
$placeid = $_GET['param'];
$serverjobid = $_GET['param'];
$serverid = $_GET['param'];
$serverplayers = $_GET['param'];
$sendername = $_GET['param'];
$senderid = $_GET['param'];
$senderage = $_GET['param'];
$senderwarnings = $_GET['param'];
$calltype = $_GET['param'];
$reportinfo = $_GET['param'];
$suspect = $_GET['suspect'];
mysql_query("INSERT INTO mss_calls3 (gamename, gameowner, gameownerid, placeid, serverjobid, serverid, serverplayers, sendername, senderid, senderage, senderwarnings, calltype, reportinfo, suspect) VALUES ($gamename, $gameowner, $gameownerid, $placeid, $serverjobid, $serverid, $serverplayers, $sendername, $senderid, $senderage, $senderwarnings, $calltype, $reportinfo, $suspect)");
};
?>
#Mark is right, you should stick to using the mysqli functions only.
As #andrewsi says, since you're not querying data, there's nothing in your code that prints whether the insert statement is a success, but only on failure, so I added a "success!" echo. You will still want to query the database to see if the values were inserted.
#Matt and #Mark's points about preparing statements are crucial to sanitizing your input - this is security 101, and you should do some googling on it.
But ultimately, I think #CodeGodie hit on your biggest problem to just getting it working. You assign all your variables to the same value with $_GET['param'] except for "suspect" at the very end. And from the link you posted in the question, there is no "param" in your query string. I'm not entirely sure what you were going for, but I'm assuming you wanted to match the parameter name with the variable name. I don't think it works that way, but the following untested code should get you going:
<?php
$params = array(
"gamename",
"gameowner",
"gameownerid",
"placeid",
"serverjobid",
"serverid",
"serverplayers",
"sendername",
"senderid",
"senderage",
"senderwarnings",
"calltype",
"reportinfo",
"suspect"
);
$cols = "";
$vals = "";
$binding_type = "";
$get_params = array();
// first pass to build the query,
// and validate inputs exist
for ($params as $param) {
if ( isset($_GET["$param"]) ) {
$cols .= "$param,";
$vals .= "?,";
$get_params []= $_GET["$param"];
// determine the binding type as either integer or string
if (is_numeric($_GET["$param"]))
$binding_type .= "i";
else
$binding_type .= "s";
} else die("$param is not set");
}
// trim trailing commas
$cols = rtrim($cols, ",");
$vals = rtrim($vals, ",");
$sql = "INSERT INTO mss_calls3 ($cols) VALUES ($vals);";
$servername = "";
$username = "";
$password = "";
$database = "";
// Establish MySQL Connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("MySafeServer Database Connection Failed: " . $conn->connect_error);
}
// prepare statement
$stmt = $conn->prepare($sql) or die($conn->error);
// bind parameters
// watch this is the tricky dynamic part I got help from the following, but may need some work:
// http://stackoverflow.com/questions/627763/php-and-mysqli-bind-parameters-using-loop-and-store-in-array
// http://no2.php.net/manual/en/mysqli-stmt.bind-param.php#89171
call_user_func_array( array($stmt, 'bind_param'), array_merge(array($stmt, $binding_type), $get_params));
// execute
if( $stmt->execute() )
echo "success!";
else
echo $stmt->error;
$stmt->close();
$conn->close();
?>
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.
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))