Mysql auto insert an empty row - php

I am working with mysql in my project and when I try to call the webAPI to insert data to the database, it inserts an empty row before the inserted row.
Can anyone help please?
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$nom = $_POST['nom'];
$query = "INSERT into class (nom_class) values('$nom')";
$result = $db->query($query);
if ($result === TRUE) {
$res = "Inserted" . $nom;
echo json_encode($res);
} else {
echo json_encode("Error" . $query . "<br>" . $db->error);
}
break;
I have tried EMPTY, and ISSET features but it didn't work.
This is the database:
I'll be so grateful if any one could help.

Related

How can i update multiple table with one query php?

if($_SERVER['REQUEST_METHOD'] == 'POST'){
$content = file_get_contents('php://input');
$user = json_decode($content, true);
$id_a = $user['id_a'];
$id_b = $user['id_b'];
$aName = $user['aName'];
$bName = $user['bName'];
$sql = "
BEGIN TRANSACTION;
UPDATE `tb1`
SET `aName` = '$aName'
WHERE `id_a` = '$id_a';
UPDATE `tb2`
SET `bName` = '$nName'
WHERE `id_b` = '$id_b';
COMMIT
";
$result = $conn->query($sql);
if($result){
echo json_encode(['status'=>'success','message'=>'Edited successfully']);
}
else{
echo json_encode(['status'=>'error','message'=>'An error occurred editing the information.']);
}
}
else{
echo json_encode(['status'=>'error','message'=>'REQUEST_METHOD Error']);
}
$conn->close();
I need to update data multiple table but when i use above code it it response "Edited successfully" but in database data didn't change anything
but when update single table it can
No need for a transaction because it seems your PDO does not accept a transaction.
Something like this should work in the example you gave:
UPDATE tb1, tb2
SET tb1.aName = $aName,
tb2.bName = $bName
WHERE
tb1.id_a = $id_a
AND tb2.id_b = $id_b;

How to display error msg if the value of id text field is not in form?

code:
if(isset($_POST["add"]))
{
extract($_POST);
$facilities = $_POST['facilities'];
$chk="";
foreach($facilities as $chk1)
{
$chk .= $chk1.",";
}
$exam = $_POST['exam'];
$chks="";
foreach($exam as $chked)
{
$chks .= $chked.",";
}
$filename = $_FILES['college_image']['name'];
$path = "college_banner/";
$move=move_uploaded_file($_FILES['college_image']['tmp_name'],$path.$_FILES['college_image']['name']);
$filename2 = $_FILES['logo']['name'];
$path2 = "college_logo/";
$move=move_uploaded_file($_FILES['logo']['tmp_name'],$path2.$_FILES['logo']['name']);
echo "insert into all_colleges(college_name,establish,approve,affiliated,address,website,about_us,city,courses,logo,college_image,phone,field,tag,video1,video2,facilities,courses_fee,short_name,state,exams,form_fee,college_commission,client_commission,form_type)values('$name','$establish','$approve','$affiliated','$address','$website','$about_us','$city','$course','$filename2','$filename','$phone2','$field','$tag','$video1','$video2','$chk','$fee','$short','$state','$chks','$form_fee','$college_commission','$client_commission','$form_type')";
$result = mysqli_query($link,$sql2);
if($result == true)
{
$msg .= "<h5 style='color:green;'>Successfull</h5>";
}
else
{
$msg .= "<h5 style='color:red;'>Error</h5>";
}
}
In database I have an auto_increment id i.e. college_id but when I remove auto_increment over college_id then it show successfull message when click on add button instead of error. So, how can I fix this problem ?
Thank You
It doesn't matter with you college_id just make sure if it is AUTO_INCREMENT then it must be PRIMARY KEY.
And in SQL query you are not assigning query to your $sql2 variable so use
echo $sql2 = "insert into all_colleges ...";
//---^ assign query in $sql2
$result = mysqli_query($link,$sql2); // <-- you are passing $sql2
1 more thing you can use implode() without using loops for checked values in a single statement like,
$chk= = implode(',',$_POST['facilities']);

How to debug query regarding $_FILES especially file inputs?

I had this query using php in inserting images after submitting the form It says "Requirements submitted succesfully" but there is no data inserted in database.
This is my code so far:
if(isset($_POST['sumit'])){
$count = count($_FILES);
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$sid = $row['user_id'];
$coll =$row['college'];
$stat = "Pending";
$query = "INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id'";
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) && $_FILES['imgreq'.$i]['size']){
$query .= ",'" . base64_encode(file_get_contents(addslashes($_FILES['imgreq'.$i]['tmp_name']))) . "'";
}else{
$query .= ",NULL";
}
}
$query .= ",'$stat','$coll')";
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
// saveimage($query);
}
else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
I dont know where did I go wrong so please if anyone can help I appreciate it. Thanks.
So it is true that I did not execute the query and forgot to put mysql_query($query); after $query .= ",'$stat','$coll')"; . And that lead me to solving another problem wherein I did not set the fields in the database to receive NULL values which is the cause of the error.
after:
$query .= ",'$stat','$coll')";
add
mysql_query($query)

How do I retrieve a single row from a table using PHP?

I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();

echo json_encode() is returning NULL

I am trying to pass data to a php page via ajax, the data gets inserted to the database, then I need to pick up the last insert and pass the back to update a select menu with that last insert selected. The database gets updated correctly, but Im getting a NULL return for the echo json_echo($data);
Been stuck on this all day, would really appreciate the help!!!
if (empty($_POST) === false && empty($errors) === true) {
$company_id = $_POST['company_id'];
$patient_id = $_POST['addpatient_id'];
$first_name = $_POST['addpatient_firstname'];
$last_name = $_POST['addpatient_lastname'];
$dob = $_POST['addpatient_dob'];
$updated = $_POST['patient_added'];
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')");
$last_patient_id = mysql_insert_id();
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $last_patient_id");
$data[] = mysql_fetch_assoc($result);
}
echo json_encode( $data );
json_encode returns false if an error happened (php manual). I would start there.
$json_string = json_encode( $data );
if( $json_string ){
echo $json_string;
}else{
echo "Error";
echo "<pre>";
print_r($data);
echo "</pre>";
}
That should at least lead you a way to debug.
EDIT: Also try add this to the beginning of the function all
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will help display errors that the mysql is throwing.
EDIT: I wanted to just fix spelling, but since I need 6 characters minimum I will mention http://jsonlint.com/ to validate what you're putting into json_encode

Categories