Error 500 malformed header from script. Bad header in PHP - php

I have a site thats works without any issues on wamp but once i host it in a bluehost account i get error 500 on both submit form and any ajax calls.
example of an error is
malformed header from script. Bad header=user_auth.php: fetch_cities.php
the user_auth.php thats the login script no need of posting it here.
Am using php 5.6 i did google and some of the solutions i found were like to check inside php.ini, no line showing magic_quotes_cpg=on or register_globals = on . Any pointers on what could be the issue is appreciated
fetch_cities.php
<?php
include('../../bin/initaccess.php');
$city = mysqli_real_escape_string($con, $_POST['city']);
$number = mysqli_real_escape_string($con, $_POST['number']);
if($number == 0){
echo "<option value=''>-- Select City --</option>";
$sql = "SELECT city_name FROM cities";
}else{
$sql = "SELECT city_name FROM cities WHERE city_name = '$city'";
}
$result = $db->query($sql);
while($row1 = mysqli_fetch_array($result)){
$city_name = $row1['city_name'];
?>
<option <?php if($city_name == $city){ echo "selected"; } ?> value='<?php echo $city_name; ?>'><?php echo $city_name; ?></option>
<?php
}
?>

Related

Data not being inserted mysql

I am building a custom CMS for myself and its going great but for some reason the system is not inserting a certain field called categories. I have a table called categories and i am able to insert those categories with no problems.
On my addnewpost.php page I have this form field that lets me select an added Category..
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value=""><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
above all that I have this to inset the data into the database in a table called posts...
<?php
if(isset($_POST["Submit"])){
$posttitle = $_POST["posttitle"];
$Category = $_POST["Category"];
$image = $_FILES["image"]["name"];
$target = "../uploads/".basename($_FILES["image"]["name"]);
$posttext = $_POST["postdescription"];
$admin = "phillip";
date_default_timezone_set("Europe/London");
$CurrentTime=time();
$DateTime=strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($posttitle)){
$_SESSION["ErrorMessage"] = "Post title cannot be empty";
redirect_to("addnewpost.php");
} elseif (strlen($posttitle)<10){
$_SESSION["ErrorMessage"] = "Post title should be greater than 10 characters";
redirect_to("addnewpost.php");
} else {
//All is good insert into the database
$sql = "INSERT INTO posts(datetime,title,category,author,image,post)";
$sql .= "VALUES(:dateTime,:postTitle,:categoryName,:adminName,:imageName,:postDescription)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':dateTime',$DateTime);
$stmt->bindValue(':postTitle',$posttitle);
$stmt->bindValue(':categoryName',$Category);
$stmt->bindValue(':adminName',$admin);
$stmt->bindValue(':imageName',$image);
$stmt->bindValue(':postDescription',$posttext);
$Execute=$stmt->execute();
move_uploaded_file($_FILES["image"]["tmp_name"],$target);
if($Execute){
$_SESSION["SuccessMessage"]="Post with id : ".$conn->lastInsertId()." Added Successfully";
redirect_to("addnewpost.php");
} else {
$_SESSION["ErrorMessage"]="Something went wrong. Try again";
redirect_to("addnewpost.php");
}
}
}
?>
Here is a screengrab showing that the category fields are empty. I do have display errors enabled but none are showing up. Any thoughts appreciated...
Thank you Nigel and Felippe. I just took out the option value so it's just this instead...
<option><?php echo $CategoryName; ?></option>
That's made it all work perfectly. Been looking at this for hours as well.
Thank you both.
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value="<?php echo $CategoryName; ?>"><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
This is more like it

PHP Query won't work with DELETE

I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)
<form class="form">
<?php
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
mysqli_query($db, $que);
}
mysqli_close($db);
?>
<span class="main-page__info">Usuń rekord zainteresowań.</span>
<select name="del_zaint">
<option disabled selected>Wybierz rekord do usunięcia</option>
<?php
require "connect.php";
$que = "SELECT * from zainteresowania";
$wynik = mysqli_query($db, $que);
while($row = mysqli_fetch_array($wynik)){
echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
}
mysqli_close($db);
?>
</select>
<input name="Del" type="submit" value="Usuń">
</form>
Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)
Try This
You miss the method in the form tag.
Also, I Change the SQL query
$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
Below code is working on my system. You have to use the SQL injection for secure
$db->real_escape_string($_POST['del_zaint'])
instated of delete the record, Make a column like status in the database and change the status 0 or 1.
You can refer the site for deleting the record
https://www.w3schools.com/php/php_mysql_delete.asp
<?php
include('db/connection.php');
if(isset($_POST['Del'])){
echo $select = $db->real_escape_string($_POST['del_zaint']);
$que = "DELETE FROM `zainteresowania` WHERE id = '".$select."'";
if (mysqli_query($db, $que)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($db);
}
mysqli_close($db);
}
?>
<form class="form" method="POST" action="#">
<span class="main-page__info">Usuń rekord zainteresowań.</span>
<select name="del_zaint">
<option disabled selected>Wybierz rekord do usunięcia</option>
<?php
$que = "SELECT * from zainteresowania";
$wynik = mysqli_query($db, $que);
while($row = mysqli_fetch_array($wynik)){
echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
}
mysqli_close($db);
?>
</select>
<input name="Del" type="submit" value="Usuń">
</form>
Please change this to:
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = $select";
mysqli_query($db, $que);
}
mysqli_close($db);
I have had cases where PHP only notices variables if they are included directly in double quotes and but not single quotes. The other option is to use string concatenation so that PHP knows where the variable is.
require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
mysqli_query($db, $que);
}
mysqli_close($db);
The main issue is you have not set method="post" with your form tag. So set it there and give it a try.
A suggestion:
Chage your query like this:
$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'"; // Check the changes I made around $select.

Inserting values from multiple checkboxes into multiple rows in a mysql database using php

I have stayed up two nights and I haven't been able to fix this. I am new to the site as well as in PHP please forgive my inexperience. The idea is that when a user selects several courses it should be sent to the database and stored in separate rows. what happens now is that it stores only the first value twice in the database. thanks.
code:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$user_id=$_SESSION['user_id'];
?>
<h2>Register</h2>
<?php
if(isset($_GET['success']) && empty($_GET['success'])){
echo 'You have successfully registered!';
}
else{
if(empty($_POST)===false){
$course[]=$_POST['course_code'];
$user_id= $user_data['user_id'];
$username=$user_data['username'];
foreach($course as $c){
$data= '\''.implode('\',\'',$c).'\'';
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUE ('$user_id','$username', $data)");
header('location:courses.php?success');
exit();
}
}
?>
<form action="" method="post">
<?php
$sql = "SELECT * FROM course";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>COURSE CODE</th><th>COURSE TITLE</th><th>UNIT</th><th>SEMESTER</th><th>LEVEL</th></tr>";
while($row = mysql_fetch_array($result)){
$course_code = $row['course_code'];
$course_title = $row['course_title'];
$course_unit = $row['course_unit'];
$semester = $row['semester'];
$level = $row['level'];
echo "<tr><td style='width: 100px;'>".$course_code."</td><td style='width: 600px;'>".$course_title."</td><td>".$course_unit."</td><td>".$semester."</td><td>".$level."</td><td><input type=\"checkbox\" name=\"course_code[]\" value=".$course_code."></td></tr>";
} // End our while loop
echo "</table>";
?>
<input type="submit" value="Register">
</form>
<?php
}
include 'includes/overall/footer.php';
?>
Your code is dangerous. It is not resistant for sql injection. You should stop using mysql_ functions and switch to mysqli or PDO.
But just to fix the bug now you can change your code in this part:
foreach($course as $c){
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`)
VALUES ('$user_id','$username', $c)");
}
header('location:courses.php?success');
exit();
redirection inside loop stopped the process so it did only once. for good practice do not put sql query inside loop it makes slow process.
$values = '';
foreach($course as $c){
$values .= "('$user_id','$username', '$c'), ";
}
$values = rtrim($values, ',');
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUES {$values}");
header('location:courses.php?success');
exit();
if you don't agree, why you don't write some comment?

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

Categories