I'm trying to get my PHP/HTML back up to scratch, and I've started by designing my own little news/whatever system. What I'm trying to do for efficiency is to run the Add/Edit/Delete all from the one process.php file via a switch($x), but for some reason it won't insert any data, and it won't give me any errors. I'm completely lost on what to do here. If anyone could help me out the code for both files is as below.
process.php
<?php
include("config.php");
if (!isset($_GET['x'])) {
$x = $_GET[x];
switch($x) {
case "add":
$title = $_POST['title'];
$text = $_POST['text'];
$date = $_POST['date'];
$author = $_POST['author'];
mysql_query("INSERT INTO posts(id, title, text, date, author) VALUES(null, '$title', '$text', '$date', '$author')") or die(mysql_error());
echo("Article inserted. Click <a href=\"index.php\" />here</a> to return.");
break;
case "gohome":
echo("Looks like you've taken a wrong turn. Click here to return.");
default:
echo("Go home.");
break;
}
} else {
$x = 'gohome';
}
?>
index.php (adding data)
<html>
<head>
<link rel="stylesheet" type="text/css" href="includes/style.css" />
</head>
<body>
<div align="center" /><font size="20px;" />test</font></div>
<?php include("includes/navigation.php"); ?>
<div align="center" />
<fieldset><legend>Submit an article</legend>
<form action="includes/process.php?x=add" method="post" />
<input name="title" type="text" value="Title" onfocus="if(this.value=='Title') this.value='';" onblur="if(this.value=='') this.value='Title';"/><br />
<input name="date" type="text" value="Date" onfocus="if(this.value=='Date') this.value='';" onblur="if(this.value=='') this.value='Date';"/><br />
<textarea rows="4" cols="50" name="text" /></textarea><br />
<input name="author" type="text" value="Author" onfocus="if(this.value=='Author') this.value='';" onblur="if(this.value=='') this.value='Author';"/><br />
<input type="submit" />
</form>
</fieldset>
</body>
</html>
This code:
if (!isset($_GET['x'])) {
$x = $_GET[x];
should be:
if (isset($_GET['x'])) {
$x = $_GET['x'];
You had the test backwards, so when the parameter was set you weren't going into the switch.
Related
I'm getting this error in my variables on lines 26 and 27. I have been searching for the problem itself, some people say that the variables are not initialized. Althought I think they are. Also I saw people saying to use isset() / !empty() but I don't understand that, and what it does.
<?php
$nome = $_POST['nome']; //26
$preco = $_POST['preco']; //27
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "crc", "root");
mysql_select_db ("crc");
$imgData =addslashes(file_get_contents($_FILES['userImage'['tmp_name']));
$sql = "INSERT INTO fios (nome,preco,imagem)VALUES('$nome','$preco','{$imgData}')";
$current_id = mysql_query($sql) or die("<b>Erro:</b> Problema na imagem inserida!<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: veradmin.php");
}}}
?>
<!DOCTYPE html>
<html>
<title>Inserir</title>
</head>
<body>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<div align="center">
</p><tr>
<td width="321"><strong>Nome/Descricao:</strong></td>
<td width="102" align="left">
<input type="text" name="nome" value="" size="40" />
</td>
</tr><p>
</p><tr>
<td width="321"><strong>Preco:</strong></td>
<td width="102" align="left">
<input type="text" maxlength="9" name="preco" value="" size="20" />
</td><p>
</p></tr>
<input name="userImage" type="file" class="inputFile" /><p>
</p><input type="submit" value="Inserir Registo" class="btnSubmit" />
</form>
</div>
</body>
</html>
This issue happened because in the first load $_POST['nome'] and $_POST['preco'] is empty and these indexes does not exists.
In this cases you should check with !empty to run this lines:
if(!empty($_POST['nome']) && !empty($_POST['preco']))
{
if(count($_FILES) > 0) {
...
}
}
At this time if you post your form or not these codes will run which is root cause of showing these notices
I tried to make a code which will add an entry to my MySQL table (called "rechnungen") via php. So I made some inputs in html and finaly I tried to insert the informations into my table (using the INSERT INTO... command). So this is what i made:
<?php
Session_Start();
$username=$_SESSION['username'];
$password=$_SESSION['password'];
$dbname=$_SESSION['dbname'];
$servername=$_SESSION['hostname'];
/*conn dev*/
$conn = mysql_connect($servername, $username, $password);
if($conn === false){
header("Location: LogIn.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title></title>
</head>
<body>
<main>
<form method="POST" action="">
<div class="form_neueRechnung">
<!-- part 1 -->
<input type="text" name="suche_Vname_Patienten" placeholder="Vorname" required="">
<input type="text" name="suche_Nname_Patienten" placeholder="Nachname" required="">
<input type="number" id="id_Patient" name="id_patient" placeholder="Pat. Nr." Value="
<?php echo $KID_output; ?>" required="">
</td>
<input type="radio" name="Behandlung" value="Osteopathie" onclick="andere()" required="">
<input type="radio" name="Behandlung" value="Krankengymnastik" onclick="andere()" required="">
<input type="radio" name="Behandlung" id="andere_Behandlung" value="andere" onclick="andere()" required="">
<input type="text" name="andereBehandlung_text" id="andereBehandlung_text" placeholder="andere" style="visibility:hidden">
<!-- part 2 -->
<input type="radio" name="rezept_rechnung" id="mit_rezept" value="mit_Rezept" onclick="rezept()" required="">
<input type="radio" name="rezept_rechnung" id="ohne_rezept" value="ohne_Rezept" onclick="rezept()" required="">
<input type="text" id="ohne_rezept_text" name="ohne_rezept_text" placeholder="freier Text">
<!-- part 3 -->
<input type="time" name="termin1_von" required="">
<input type="time" name="termin1_bis" required="">
<input type="date" name="termin1_date" required="">
<!-- submit -->
<input type="submit" class="submit" value="Rechnug erstellen" name="submit" id="submit">
</div>
<div class="form_fieldset" id="rezept_einstellungen" style="visibility:hidden">
<input type="date" id="rezept_datum" name="rezept_datum">
<input type="text" id="rezept_verordnung" name="rezept_verordnung">
<input type="text" id="rezept_diagnose" name="rezept_diagnose">
</div>
</form>
<script type="text/javascript">
function andere() {
if (document.getElementById('andere_Behandlung').checked) {
document.getElementById('andere_BehandlungArt').style.visibility = 'visible';
} else {
document.getElementById('andere_BehandlungArt').style.visibility = 'hidden';
}
}
function rezept() {
if (document.getElementById('mit_rezept').checked) {
document.getElementById('rezept_einstellungen').style.visibility = 'visible';
} else {
document.getElementById('rezept_einstellungen').style.visibility = 'hidden';
}
if (document.getElementById('ohne_rezept').checked) {
document.getElementById('ohne_rezept_text').style.visibility = 'visible';
} else {
document.getElementById('ohne_rezept_text').style.visibility = 'hidden';
}
}
</script>
<?php
mysql_connect("$servername","$username","$password") or die("connection failed!");
mysql_select_db($dbname) or die ("no database found");
$query = mysql_query("SELECT * FROM `rechnungen`");
while($row = mysql_fetch_array($query)){
$RID = $row['RechnungsID'];
}
$RechnungsID = max($RID ,$RID)+1;
echo $RechnungsID;
$mit_ohne_Rezept = "";
if(isset($_POST['submit'])) {
if($_POST['rezept_rechnung'] == "mit_Rezept") {
$mit_ohne_Rezept = "1";
}
else {
$mit_ohne_Rezept = "0";
}
}
if(isset($_POST['submit'])){
$KundenID=$_POST['id_patient'];
$Behandlung=$_POST['Behandlung'];
$Rezept_datum=$_POST['rezept_datum'];
$Rezept_Verordnung=$_POST['rezept_verordnung'];
$Rezept_Diagnose=$_POST['rezept_diagnose'];
$ohneRezept_text=$_POST['ohne_rezept_text'];
mysql_select_db($dbname,$conn);
$result = "INSERT INTO rechnungen (`RechnungsID`, `KundenID`, `Behandlung`, `mit_ohne_Rezept`, `Rezept_datum`, `Rezept_Verordnung`, `Rezept_Diagnose`, `ohneRezept_text`)
VALUES ('$RechnungsID','$KundenID','$Behandlung','$mit_ohne_Rezept','$Rezept_datum','$Rezept_Verordnung','$Rezept_Diagnose','$ohneRezept_text)";
if (mysql_query($result)) {
echo ("finished!");
} else {
echo "error". mysql_error();
}
}
mysql_close($conn);
?>
</main>
</body>
</html>
I know it's a pretty long code, but i don't know where the problem could be. I'm getting this error:
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sdfas)' at line 2
please help me. I'm despairing.
','$ohneRezept_text)";
looks like the issue is here.
missing a quotation mark?
that's what the error is saying
also you don't need to wrap variables in quotations, well you can but its still a pain. if your input contains quotation marks it skips right out. Use addslashes()
I have a PHP script that works on Linux but not on Windows.
I can accept that my PHP coding isn't that great, I'm a newbie.
I have a form, and I post the data to it. Now that it is on a Windows server, I get:
Notice: Undefined index: nmr in C:\Apache24\htdocs\index.php on line 31
...
and so on.
I tried declaring all the variables as 0, and using isset, but it doesn't seem to work.
Perhaps I'm using isset wrong. Can someone help me?
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="http://www.hackmaine.org/favicon.ico">
<link rel="stylesheet" type="text/css" href="sty.css">
<title>NMR Scheduler</title>
</head>
<body>
<?PHP
$Unity = 'unchecked';
$Inova = 'unchecked';
$Experiment = $duration = $ToD = $startTime = $ddate = $nmr = $UName = 0;
if (isset($_POST['Submit1']))
{
$selected_radio = $_POST['nmr'];
switch ($selected_radio)
{
case Unity:
break;
case Inova:
break;
default:
echo "Select an NMR";
}
}
isset($Experiment, $duration, $ToD, $startTime, $ddate, $UName);
$reg_wvar=$_POST['nmr'];
$reg_UName=$_POST['UName'];
$reg_Date=$_POST['ddate'];
$reg_startTime=$_POST['startTime'];
$reg_ToD=$_POST['ToD'];
$reg_duration=$_POST['duration'];
$reg_Experiment=$_POST['Experiment'];
$stringy = "$reg_wvar, $reg_UName, $reg_Date, $reg_startTime $reg_ToD, $reg_duration, $reg_Experiment \n";
echo $stringy;
$filename = 'newEntry.txt';
// Let's make sure the file exists and is writeable first.
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $stringy) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "Data not written, Make Sure you selected an NMR";
}
?>
<center>
<FORM ACTION="if.php" method="post">
<h2>NMR Usage Scheduler</h2>
<br /><br />
<INPUT TYPE = 'Radio' Name ='nmr' value= 'Unity'>Unity
<INPUT TYPE = 'Radio' Name ='nmr' value= 'Inova' >Inova<br /><br />
<B>Your Name :</B><input type="text" size="20" maxlength="10" name="UName" required><br /><br />
<B>Enter Date (mm/dd):</B> <input type="text" size="20" maxlength="5" name="ddate" required><br /><br />
<B>Start Time (hh:mm):</B> <input type="text" size="8" maxlength="5" name="startTime" required>
<INPUT TYPE = 'Radio' Name ='ToD' value= 'AM' >AM
<INPUT TYPE = 'Radio' Name ='ToD' value= 'PM' checked>PM
<br /><br />
<B>Duration: </B> <input type="text" size="20" maxlength="5" name="duration" required><br /><br />
<B>Experiment:</B> <input type="text" size="20" maxlength="5" name="Experiment" required><br /><br />
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Submit">
</FORM>
</center>
</body>
</html>
if(isset($_POST['nmr'], $_POST['UName'], ...) {
$reg_wvar=$_POST['nmr'];
$reg_UName=$_POST['UName'];
...
}
I am currently creating a cms, all is fine apart from the add.php page.
My code for this page is this:
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$image = $_POST['Image URL'];
$link = $_POST['Link'];
$price = $_POST['Price'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
$query->execute(array(
':title' => $title,
':content' => $content,
':image' => $image,
':link' => $link,
':price' => $price
));
$query->execute();
}if($result){
echo("<br>Input data is successful");
} else{
echo("<br>Input data failed");
}
}
?>
<html>
<head>
<title>testing</title>
<link rel="stylesheet" href="../style.css" />
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form name = "myform" action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input type="text" name="Image URL" placeholder="Image URL" /><br /><br />
<input type="text" name="Link" placeholder="Link" /><br /><br />
<input type="text" name="Price" placeholder="Price" /><br /><br />
<input type="submit" name="submit" value="Add Article" />
</form>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
error_reporting(E_ALL);
?>
My problem is. My code is not showing any errors in my error log and people tellme that it is fine. But it is not adding to the database. is there a way that I can break down each bit of code and find out what is going on?
or is there a way to display what the error may be? my error reporting is turned on with E_ALL | E_STRICT and still nothing.
please help
thank you.
You need to change your PDO query from
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
to be something like this
$query = $pdo->prepare('INSERT INTO `apps`(`app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:title,:content,:img,:link,:price)');
You should review how PDO::prepare method work with placeholders. Besides, if your app_id is an auto increment field. You need not include it in your insert query.
I'm not sure how this could work as the placeholders aren't using the correct notation and aren't named correctly.
Your query should look like:
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:app_id, :app_title, :app_content, :app_img, :app_link, :app_price)');
$query->execute(array(
':app_id' => ???,
':app_title' => $title,
':app_content' => $content,
':app_img' => $image,
':app_link' => $link,
':app_price' => $price
));
Also you appear to be missing the :app_id parameter.
I am noob in CI and I can't insert a data in database, here is all I have done, it doesn't show me an error but i don't get a result,
admin.php (controller)
public function postnews(){
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == "my ip address"){
session_start();
if (!isset($_SESSION['admin'])){
$this->load->view('admin-login');
die(0);
}
if ($_SESSION['admin'] != 'loged'){
$this->load->view('admin-login');
die(0);
}
if ($_SESSION['admin'] == 'loged'){
if (isset($_POST['title'])and isset($_POST['main-poster']) and isset($_POST['type']) and isset($_POST['year']) and isset($_POST['language'])and isset($_POST['platform'])and isset($_POST['publisher'])and isset($_POST['size'])and isset($_POST['graphics'])and isset($_POST['little-info'])and isset($_POST['full-info'])and isset($_POST['posters'])and isset($_POST['screenshots'])and isset($_POST['trailers'])and isset($_POST['gameplays'])and isset($_POST['author'])){
$title = $_POST['title'];
$main_poster = $_POST['main-poster'];
$type = $_POST['type'];
$year = $_POST['year'];
$language = $_POST['language'];
$platform = $_POST['platform'];
$publisher = $_POST['publisher'];
$size = $_POST['size'];
$graphics = $_POST['graphics'];
$little_info = $_POST['little-info'];
$full_info = $_POST['full-info'];
$posters = $_POST['posters'];
$screenshots = $_POST['screenshots'];
$trailers = $_POST['trailers'];
$gameplays = $_POST['gameplays'];
$autor = $_POST['author'];
$date = date("d.m.Y");
$this->load->model('Gamesmodel');
echo $this->Gamesmodel->PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date);
}else{
$this->load->view('postnews');
}
}
} else {
$this->load->view('404.htm');
die(0);
}
}
gamemodel.php model
<?php
class Gamesmodel extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date)
{
$sql = "INSERT INTO game-articles (id, title, type, year, language, platform, publisher, size, graphics, little-info, full-info, posters, screenshots, trailers, gameplays, date, author) VALUES ('' ,".$this->db->escape($title).",".$this->db->escape($main_poster).",".$this->db->escape($type).",".$this->db->escape($year).",".$this->db->escape($language).",".$this->db->escape($platform).",".$this->db->escape($publisher).",".$this->db->escape($size).",".$this->db->escape($graphics).",".$this->db->escape($little_info).",".$this->db->escape($full_info).",".$this->db->escape($posters).",".$this->db->escape($screenshots).",".$this->db->escape($trailers).",".$this->db->escape($gameplays).",".$this->db->escape($date).",".$this->db->escape($author).")";
$this->db->query($sql);
return $this->db->affected_rows();
}
}
postnews.php view
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Post News</title>
</head>
<body style="background-color:black;">
<div style="margin:auto auto auto auto; width:800px; background-color:white; padding-top:20px; padding-bottom:20px; text-align:center;">
<form action="http://www.gameslib.net/admin/postnews" method="post"><br />
<input type="text" placeholder="title" name="title" style="width:300px;" /><br />
<input type="text" placeholder="main poster" name="main-poster" style="width:300px;" /><br />
<input type="text" placeholder="type" name="type" style="width:300px;" /><br />
<input type="text" placeholder="year" name="year"/><br />
<input type="text" placeholder="language" name="language" style="width:300px;" /><br />
<input type="text" placeholder="platform" name="platform" style="width:300px;" /><br />
<input type="text" placeholder="publisher" name="publisher" style="width:300px;" /><br />
<input type="text" placeholder="size" name="size"/><br />
<input type="text" placeholder="graphics" name="graphics" style="width:300px;" /><br />
<textarea name="little-info" placeholder="little-info" style="width:600px; height:100px;" ></textarea><br />
<textarea name="full-info" placeholder="full-info" style="width:600px; height:200px;" ></textarea><br />
<textarea name="posters" placeholder="posters" style="width:600px; height:50px;" ></textarea><br />
<textarea name="screenshots" placeholder="screenshots" style="width:600px; height:50px;" ></textarea><br />
<textarea name="trailes" placeholder="trailes" style="width:600px; height:50px;" ></textarea><br />
<textarea name="gameplays" placeholder="gameplays" style="width:600px; height:50px;" ></textarea><br />
<input type="text" placeholder="author" name="author" /><br />
<input type="submit" value="P O S T"/><br />
<input type="reset" value="reset"/><br />
</form>
</div>
</body>
</html>
please help me, I copied allmost everything to be shure I am not ignoring something,
Ok, lets start by clearing up your code. Instead of having to create each independent variable in your if ($_SESSION['admin'] == 'loged') method, you can use the function extract();. The extract() method creates a variable for each key in the provided array. Say you have the key name in the array $_POST, the extract method will create a variable named name for you. To retrieve the value, all you need to do is access the variable $name.
if ($_SESSION['admin'] == 'loged'){
extract($_POST);
}
Secondly, you don't use the word and if you want to check more than one thing in an if statement, you use the following operand '&&'.
if (isset($_POST['title']) && isset($_POST['main-poster']) && isset($_POST['type']) && isset($_POST['year']) && isset($_POST['language']) && isset($_POST['platform']) && isset($_POST['publisher']) && isset($_POST['size']) && isset($_POST['graphics']) && isset($_POST['little-info']) && isset($_POST['full-info']) && isset($_POST['posters']) && isset($_POST['screenshots']) && isset($_POST['trailers']) && isset($_POST['gameplays']) && isset($_POST['author']))
Instead of manually checking to see if each object has been set in the $_POST array, you can just iterate through $_POST.
Create an array of the variables that you need to be set:
$req_fields = array(
'title',
'main-poster',
'type',
'year',
'language',
'platform',
'publisher',
'size',
'graphics',
'little-info',
'full-info',
'posters',
'screenshots',
'trailers',
'gameplays',
'author'
);
Then create an array for the elements that haven't been set:
$notset = array();
Finally, iterate through $_POST checking to see if each value is set. If not, add it to the array.
foreach ($req_fields as $key) {
if (!isset($_POST[$key]) {
$notset[] = $key;
}
}
Then check to see if any values have not been set and redirect the user, else, load the model and echo the post:
if (count($notset) > 0) {
$this->load->view('postnews');
}
else {
$this->load->model('Gamesmodel');
echo $this->Gamesmodel->PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date);
}
Presumably the actual reason behind the insert not working is because it isn't actually called. The reason behind this would be that some of the keys were not actually set.
Iterate through the $notset array to see if this is the case:
foreach ($notset as $unsetField) {
echo "Field {$unsetField} is not set. <br />";
}