Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
It was working fine just a while ago I was getting JSON response, which was an array of JSON objects now it shows a blank page ,I have no idea why! Can anyone identify what's the problem here?
here is the php code:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="tourist"; // Database name
// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
if($con){
mysqli_set_charset($con ,'utf8');
$qry = "SELECT * FROM places";
$query=mysqli_query($con ,$qry);
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}
$return_arr = array();
$row_array = array();
$num_rows = mysqli_num_rows($query);
if ($num_rows > 0) {
while ($r = mysqli_fetch_array($query)) {
$row_array['place_id'] = $r['place_id'];
$row_array['place_name'] = $r['place_name'];
//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//$row_array['image'] = "http://localhost/tourist/". $r['db_image']; //.'" alt=\"\" /"';
$row_array['image'] = "tourist/".$r['db_image'];
$row_array['des'] = $r['description'];
header('Content-Type: application/json');
array_push($return_arr,$row_array);
}
return json_encode($return_arr);
} else {
$return_arr['place_name'] = 'ERRO - Place inexistente';
}
header('Content-Type: application/json');
echo json_encode($return_arr);
return json_encode($return_arr);
mysqli_close($con);
} else {
$return_arr['place_name'] = 'ERRO - failure';
echo json_encode($return_arr);
return json_encode($return_arr);
}
?>
There are a few error in here
First you are mixing database access API's you cannot use mysql_ and mysqli_ calls. as you are connecting with mysqli_ stick with that
Secondly you do not use a return unless you are in a function. Used as you have it is killing the script the first one it comes across in the normal flow of the code, and of course NOT sending the data back to your browser.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="tourist"; // Database name
// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
if($con){
mysqli_set_charset($con ,'utf8');
$qry = "SELECT * FROM places";
$query=mysqli_query($con ,$qry);
if (!$query) {
//$message = 'Invalid query: ' . mysql_error() . "\n";
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}
$return_arr = array();
$row_array = array();
$num_rows = mysqli_num_rows($query);
if ($num_rows > 0) {
while ($r = mysqli_fetch_array($query)) {
$row_array['place_id'] = $r['place_id'];
$row_array['place_name'] = $r['place_name'];
//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//$row_array['image'] = "http://localhost/tourist/". $r['db_image']; //.'" alt=\"\" /"';
$row_array['image'] = "tourist/".$r['db_image'];
$row_array['des'] = $r['description'];
header('Content-Type: application/json');
array_push($return_arr,$row_array);
}
// This will be terminating the script
//return json_encode($return_arr);
} else {
$return_arr['place_name'] = 'ERRO - Place inexistente';
}
header('Content-Type: application/json');
echo json_encode($return_arr);
// not needed
//return json_encode($return_arr);
mysqli_close($con);
} else {
$return_arr['place_name'] = 'ERRO - failure';
echo json_encode($return_arr);
// Not needed
//return json_encode($return_arr);
}
?>
Related
I am trying to input data to MySQL using PHP. Don't know what's wrong. The connection succeeds, no errors but at the end there is not data being written to the database.
$dbhost = "localhost";
$dbname = "listings";
$un = $_POST["un"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$des = $_POST["des"];
$quan = $_POST["quantity"];
$specs = $_POST["specs"];
$price = $_POST["price"];
$url1 = ".";
$url2 = ".";
$url3 = ".";
$url4 = ".";
$connection = mysqli_connect($dbhost,$un,$pass,$dbname);
if (!$connection) {
die("Error".mysqli_error);
} else {
echo "Database connection successfull ".$des;
}
$query = "INSERT INTO items
(name,description,quantity,specs,price,url1,url2,url3,url4) VALUES
'$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')
";
echo "Hellos";
$exeute_query = mysqli_query($query,$connection);
if(!execute_query){
die("error ".mysqli_error());
echo "query error";
} else {
echo "Query successfull";
}
mysqli_close($connection);
Any help?
There are several small mistakes in your code:
$query = "INSERT INTO items (name,description,quantity,specs,price,url1,url2,url3,url4) VALUES ('$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')";
echo "Hellos";
**$exeute_query** = mysqli_query($query,$connection); // $execute_query instead of $exeute_query
if(!**execute_query**){ //$execute_query instead of execute_query
die("error ".mysqli_error());
echo "query error";
}
else{echo "Query successfull";}
mysqli_close($connection);
?>
Your code breaks at the if statement because no fucntion with that name is found (if you do not use the dollarsign to show it is a variable, php will interpret it as a function. Also, when initiating your variable you forgot a 'c' so make sure to check if you have the correct variable name or php won't find your variable. Now your query will work or give an error message in case of wrong data formats or bad connection. Use code listed below to debug your php in the future.
error_reporting(E_ALL);
ini_set('display_errors', 'On');
I have this php file and I want to echo one array that ticketnumber is located in it with json encode, in meaning I want to print only one array when isset POST the ticketnumber for this array, but I tried and every time I get error how to slove this problem in addition I used the loop (while) so is it correct for one array?
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS','');
define('DB', 'ala');
$con = mysqli_connect(HOST,USER,PASS,DB) or die ('unable to connect');
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[0], 'subject' =>$get[1],'response' =>$get[2]));
}
if(isset($get)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
You don't define variable $get .
I thinks there should be..
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
Try like this..
if(!empty($get)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
Ok so I wrote some code to find records on a test database, it works if there is a record and does display the data, if there is no record it still says that it found stuff. It should say it did not. It even finds stuff that is not in the database but obviously has no data to display, its annoying.
I need a new pair of eyes.
I think the error is here:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
But just in case here is the full code minus the login credentials to the db.
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
if ($result)
{
$OutputMessage = 'Record Found';
}
There is your mistake, that means if the query executed successfully (even with 0 records) you are saying records found. You should only say that if the number of records returned are more than 0.
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
But the bigger problem with your code can be solved by this reading
How can I prevent SQL injection in PHP?
This may happen, because if $_POST['KittenID'] is empty, the sql query would look like : SELECT * FROM Kittenzz WHERE KittenID=""; you have to change the above if statement to:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.