I'm making a form for some project. The problem is when the user enter their data using the field and then submit, the input not keep in the database.
Also when clicking submit the direct page show blank empty page even the connection test also not showing.
I'm using almost similar code for other project and it work except for this.
below is my code:
<?php
//check connection
require 'config.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//asas (table name)
$id = $_POST["Sid"]; $ic = $_POST["Sic"];
$name = $_POST["Snp"]; $jant = $_POST["J1"];
$trum = $_POST["Chr"];$tbim = $_POST["Chp"];
$mel = $_POST["Sem"]; $arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"]; $uni = $_POST["Sis"];
$bid = $_POST["tpe"];$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];$bik = $_POST["B1"];
$tem = $_POST["te"];$mula = $_POST["tm"];
$tamm = $_POST["tt"]; $res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];$keb = $_POST["fileToUpload3"];
$link = mysqli_connect($h,$u,$p,$db);
if('id' != '$Sid'){
$asas = "insert into asas Values ('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values ('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
mysqli_query($link,$asas);
mysqli_query($link,$inst);
mysqli_query($link,$indr);
mysqli_close($link);
}
else
{
echo "failed"
}
?>
<b>Register complete</b>
Can anybody tell me what the error or maybe some solution. Thanks
I think you are having problem in insert query, please check this:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
Write this kind.
thank you
there are few issues with the code like variable id was used without $
and need to use die method with mysqli_query() function to check for
errors, please check below improved codes, it may help you -
<?php
//check connection
require 'config.php';
if (isset($_POST)) {
//asas (table name)
$id = $_POST["Sid"];
$ic = $_POST["Sic"];
$name = $_POST["Snp"];
$jant = $_POST["J1"];
$trum = $_POST["Chr"];
$tbim = $_POST["Chp"];
$mel = $_POST["Sem"];
$arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"];
$uni = $_POST["Sis"];
$bid = $_POST["tpe"];
$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];
$bik = $_POST["B1"];
$tem = $_POST["te"];
$mula = $_POST["tm"];
$tamm = $_POST["tt"];
$res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];
$keb = $_POST["fileToUpload3"];
}
$link = mysqli_connect($h, $u, $p, $db);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
// if('id' != '$Sid'){
if ($id != '$Sid') {
$asas = "insert into asas Values
('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values
('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
if (mysqli_query($link, $asas)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $inst)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $indr)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
}
mysqli_close($link);
?>
<b>Register complete</b>
just use or die after mysqli_query
mysqli_query($link,$asas)or die ('Unable to execute query. '. mysqli_error($link));
you will get to know what is the actual problem
Related
I am trying to update a column of a database's table using this
$url = mysqli_connect($servername, $dbusername, $usrpassword, $dbname);
// Check connection
if (!$url) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT adv_val FROM current_advert";
if($result = mysqli_query($url, $sql)){
while($row = mysqli_fetch_assoc($result)){
$adv_val = $row['adv_val'];
}
}
echo "current advert is:" . $adv_val;
// Attempt select query execution
$sql = "SELECT advert_text FROM advertisements WHERE advert_id = $adv_val";
if($result = mysqli_query($url, $sql)){
while($row = mysqli_fetch_assoc($result)){
$advert = $row['advert_text'];
}
}
echo "<br>current advert text is:" . $advert;
if ($adv_val == 1 OR $adv_val == 2 OR $adv_val == 3) {
$adv_val = $adv_val + 1;
} else {
$adv_val = 1;
}
$sql = "UPDATE current_advert SET adv_val='$adv_val'";
// Close connection
echo "<br>next advert id is:" . $adv_val;
mysqli_close($url);
The connection to the database is ok since i'm able to read data from it in the beginning of my script. This is killing me!
$sql = "UPDATE current_advert SET adv_val='$adv_val'";
mysqli_query($url, $sql);
you are missing the 2nd line.
I am new in PHP and I'm currently working with a module of Setting an operation wherein I will insert data from a modal into the database. There's no error in terms of getting the data but when I click the button, the "Query failed: INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('vbv','12:09','17:09','4')" always being displayed.
Here's the code for the db class..
var $hostname = "REDACTED";
var $username = "REDACTED";
var $password = "REDACTED";
var $database = "REDACTED";
function select_db() {
$result = mysqli_connect($this->hostname,$this->username,$this->password);
if (!mysqli_select_db( $result, $this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result1 = mysqli_connect($this->hostname,$this->username,$this->password);
$result = mysqli_query($result1,$query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
function num_rows($result) {
return mysqli_num_rows($result);
}
function last_insert_id() {
return mysqli_insert_id();
}
function kill() {
mysqli_close();
}
}
?>
and here's the code for inserting the data.
<?php
if (isset($_POST['btnSubmit'])) {
$db = new mysqldb();
$db->select_db();
$result1 = mysqli_connect("REDACTED","REDACTED","REDACTED");
$sql_mobilvis = sprintf("INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('%s','%s','%s','%s')",
mysqli_real_escape_string($result1,$_POST['location']),
mysqli_real_escape_string($result1,$_POST['starttime']),
mysqli_real_escape_string($result1,$_POST['endtime']),
mysqli_real_escape_string($result1,$_POST['mobilnum']));
$result_user = $db->query($sql_mobilvis);
if ($_POST['fields']){
$inserted_mobilvis_id = $db->last_insert_id();
foreach ( $_POST['fields'] as $key=>$value ) {
$sql_enforcer = sprintf("INSERT INTO tbl_mobilenforcer (enforcername) VALUES ('%s')",
mysqli_real_escape_string($result1, $value) );
$result_website = $db->query($sql_enforcer);
$inserted_enforcer_id = $db->last_insert_id();
$sql_mobil_enforcer = sprintf("INSERT INTO tbl_mobil (mobilid, mobilenforcerid) VALUES ('%s','%s')",
mysqli_real_escape_string($result1,$inserted_mobilvis_id),
mysqli_real_escape_string($result1,$inserted_enforcer_id) );
$result_mobil_enforcer= $db->query($sql_mobil_enforcer);
}
} else {
echo "<script>alert('no added enforcers')</script>";
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> enforcers are added!</h1>";
$db->kill();
}
?>
Why I am getting this Query failed?
The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?
It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);
You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>
I try to parse a xml file and store each node to a mysql db. The problem is that it store the data in the first loop and returns error in the second time. If I refresh the page it stores the rest data as well.
I try to understand why does it behave in a such way
<?php
try{
$records = simplexml_load_file("file.xml");
} catch (Exception $e){
echo "xml problem";
}
#replace loclhost,user, pass, dbname
$db = mysqli_connect("localhost", "root", "", "project") or die("could not connect:" . mysqli_connect_error());
foreach($records->record as $rec){
$species_location_x = $rec->species_lang;
$species_location_y = $rec->species_long;
$species_abundance = (string)$rec->abundance;
$species_text = (string)$rec->text;
$species_scene_photo = (string)$rec->space_photo;
$species_photo_loc = (string)$rec->specimen_photo;
$site_name = (string)$rec->site->sitename;
$site_location = (string)$rec->site->sitelocation;
$site_description = (string)$rec->site->sitedescription;
$user_name = (string)$rec->user->lastname;
$user_phone = (string)$rec->user->namephone;
$user_email = (string)$rec->user->useremail;
$species_name = (string)$rec->species->species_name;
#print_r($species_location_x." ".$species_location_y." ".$species_abundance." ".$species_text." ".$species_scene_photo." ".$species_photo_loc);
#print_r($site_name." ".$site_location." ".$site_description);
#print_r($user_name." ".$user_phone." ".$user_email);
#print_r($species_name);
$multiq = "INSERT INTO users (user_name, user_phone, user_email)
VALUES ('$user_name', '$user_phone', '$user_email');" ;
$multiq .= "INSERT INTO records (user_name, record_location, record_abundance, record_text, record_scene_photo_location, record_specimen_photo_location )
VALUES ( '$user_name',
GeomFromText('point($species_location_x $species_location_y)'),
'$species_abundance',
'$species_text',
'$species_scene_photo',
'$species_photo_loc');" ;
$multiq .= "INSERT INTO species (species_name, records_id )
VALUES ( '$species_name', (select record_id from records where user_name = '$user_name' and record_abundance = '$species_abundance' and record_text = '$species_text'));" ;
$multiq .= "INSERT INTO sites (site_name, site_location, site_description, species_id)
VALUES ('$site_name', '$site_location', '$site_description', (select species_id from species where species_name='$species_name'));";
if(mysqli_multi_query($db, $multiq)){
echo "records added successfully\n";
}
else{
echo "problem";
}
}
mysqli_close($db);
So i am having this issue. The code is for art gallery calendar. The code has worked for this day but now it has broken down. I wrote it about 1-2 months ago and now they contacted me that something is wrong. Here is the code
<?php
require('config.php');
if(isset($_POST['lisaa_pvm'])) {
$alkupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['alkupvm'])));
$loppupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['loppupvm'])));
$muuta = mysql_real_escape_string($_POST['muuta']);
$result = mysql_query("INSERT INTO kipina_kalenteri VALUES ('','$alkupvm','$loppupvm','','','','','$muuta')") or die (mysql_error());
$tapahtuma_id = mysql_insert_id();
header('location: lisaa_tapahtuma.php?tid='.$tapahtuma_id);
}
if(isset($_POST['lisaa_tapahtuma'])) {
// siivotaan syötteet
foreach ($_POST as $key => $value) {
mysql_real_escape_string($value);
${"$key"} = $value;
}
$url = ROOT.'/files/';
if($_FILES['kuva1']['size'] > 0) {
$target = $url . $_FILES['kuva1']['name'];
if(move_uploaded_file($_FILES['kuva1']['tmp_name'], $target)) {
$kuva[] = "kuva_1 = '".basename( $_FILES['kuva1']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva2']['size'] > 0) {
$target = $url . basename( $_FILES['kuva2']['name']);
if(move_uploaded_file($_FILES['kuva2']['tmp_name'], $target)) {
$kuva[] = "kuva_2 = '".basename( $_FILES['kuva2']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva3']['size'] > 0) {
$target = $url . basename( $_FILES['kuva3']['name']);
if(move_uploaded_file($_FILES['kuva3']['tmp_name'], $target)) {
$kuva[] = "kuva_3 = '".basename( $_FILES['kuva3']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if(isset($kuva)) {
$kuvat = ", ".implode(',',$kuva);
}
if(isset($sama) AND $sama != '') {
$update = "UPDATE kipina_kalenteri SET $paikka = $sama $kuvat WHERE id = $kalenteri";
mysql_query($update) or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} elseif(isset($update)) {
$update = "UPDATE kipina_tapahtuma SET
taiteilija = '$taiteilija',
nimi = '$nimi',
kuvaus = '$kuvaus',
kuvaus = '$lyhyt_kuvaus'
$kuvat
WHERE
id = $update";
$result = mysql_query($update) or die (mysql_query());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} else {
$insert = mysql_query("INSERT INTO kipina_tapahtuma VALUES ('','$taiteilija','$nimi','$lyhyt_kuvaus','$kuvaus','$kuva[0]','$kuva[1]','$kuva[2]')") or die (mysql_error());
$tid = mysql_insert_id();
$update = mysql_query("UPDATE kipina_kalenteri SET $paikka = $tid WHERE id = $kalenteri") or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
}
}
I hope i get answer soon
Someone added or deleted one of the columns in table kipina_kalenteri or kipina_tapahtuma. Because of such situations it's better to always declare to which columns you want to insert.
So it should be like that:
INSERT INTO table (`column1`, `column2`) VALUES ('values1', 'values2');
It's about your table fields. Please define the table field before you start insert a data:
$result = mysql_query("INSERT INTO kipina_kalenteri (`field1`,`field2`,`field3`) VALUES ('$alkupvm','$loppupvm','$muuta')") or die (mysql_error());
so you can sure if the fields are matched with your data