How can I successfully edit in my update php code? - php

I'm looking for solution on how to edit the inside of my modal -the title and the note. Below is my code, I want to edit inside the button which is in modal. After successfully updated the data, I want to display the updated data by calling the homepage (hh.php) which is in my code.
Below is my code:
<?php
if(isset($_GET['id'])){
$con=mysqli_connect("localhost","root","","task");
$qi=mysqli_query($con,"SELECT * FROM note WHERE id = ".$_GET['id']);
while($row=mysqli_fetch_assoc($qi)){
$tit = $row['title'];
$not = $row['note'];
}
}
?>
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<style>
body
{
margin:0;
}
.submitted{
margin:0px;
}
.modal
{
width:100%;
height:100%;
position:fixed;
top:0;
display:none;
}
.modal_close
{
width:100%;
height:100%;
background:rgba(0,0,0,.8);
position:fixed;
top:0;
}
.close
{
cursor:pointer;
}
.note{
text-align:center;
}
#note{
font-family: Javanese text;
}
.call_modal{
font-family: myFirstFont;
}
.modal_main
{
width:50%;
height:400px;
background:#fff;
z-index:4;
position:fixed;
top:16%;
border-radius:4px;
left:24%;
display:none;
-webkit-animation-duration: .5s;
-webkit-animation-delay: .0s;
-webkit-animation-fill-mode: both;
-moz-animation-fill-mode: both;
-o-animation-fill-mode: both;
-webkit-backface-visibility: visible!important;
-webkit-animation-name: fadeInRight;
}
#-webkit-keyframes fadeInRight{0%{opacity:0;-webkit-transform:translateX(20px)}100%{opacity:1;-webkit-transform:translateX(0)}}
::-webkit-input-placeholder{
font-size: 13.4px;
}
button
{
padding:20px;
border-radius:5px;
background:#808080;
border:none;
font-size:18px;
color:#fff;
margin:8%;
}
</style>
<script>
$(document).ready(function(){
$(".call_modal").click(function(){
$(".modal").fadeIn();
$(".modal_main").show();
});
});
$(document).ready(function(){
$(".close").click(function(){
$(".modal").fadeOut();
$(".modal_main").fadeOut();
});
});
$(document).ready(function(){
$(".submitted").click(function(){
$(".modal").fadeOut();
$(".modal_main").fadeOut();
});
});
</script>
</head>
<body>
<button class="call_modal" style="cursor:pointer;"> Edit Task </button>
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<div class="note"> <?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="name">Task Name:<textarea name="title" rows="1.8" cols="20" style="margin-top: 50px"><?php echo $tit;?></textarea></div>
<textarea name="note" rows="15" cols="90" style="margin-top: 20px" placeholder="Note"><?php echo $not;?></textarea>
<br><br>
<input type="submit" name="submit" class="submitted" value="Submit">
<?php
$con=mysqli_connect("localhost","root","","task");
if(isset($_POST['submit'])){
$message=$_POST['note'];
$title=$_POST['title'];
$qw='UPDATE note SET title = $title, note = $message';
mysqli_query($con,$qw);
$r="SELECT * FROM note";
$result = mysqli_query($con, $r);
while($row = mysqli_fetch_assoc($result)){
if($row['title']==$_POST['title']){
header("location:hh.php");
}
else{
echo 'Title already exist!';
}
}
}
?>
</form>
<img src="i783wQYjrKQ.png" class="close" style="line-height: 12px;
margin-top: 1px;
margin-right: 2px;
position:absolute;
top:0;
right:0;">
</div>
</div>
</body>
</html>

Taking a quick look at the code, you are leaving yourself wide open to a SQL injection attack.
<?php
if(isset($_GET['id']))
{
$con = mysqli_connect("localhost","root","","task");
$qi = mysqli_query($con, "SELECT 'title', 'note' FROM note WHERE id = ".$_GET['id']);
$row = mysqli_fetch_assoc($qi))
$tit = $row['title'];
$not = $row['note'];
}
?>
I'd look at using PHP PDO library to safe guard against using values passed in from a web page directly in SQL code.
I'd use something more akin to:
$host = 'localhost';
$db = 'task';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$stmt = $pdo->prepare('SELECT title, note FROM note WHERE id = :id');
$stmt->execute(['id' => $_GET['id']]);
$row = $stmt->fetch();
$tit = $row['title'];
$not = $row['note'];
Obviously the connection details etc would be held in a separate external file such that they don't have to be included with every PHP file where DB access is required.

Related

PHP ChatRoom. Username is not showing, only messages

I'm trying to make a Chat Room using PHP ( It is working BTW ), but only the messages are displaying, not their usernames. I have created the Databases for them, username and msg. I don't know why their usernames aren't displaying
<? php
//$uname = $_REQUEST['uname'];
//$msg = $_REQUEST['msg'];
$uname = (isset($_REQUEST['uname']) ? $_REQUEST['uname'] : '');
$msg = (isset($_REQUEST['msg']) ? $_REQUEST['msg'] : null);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('chatbox', $con);
mysql_query("INSERT INTO logs (`username` , `msg`) VALUES ('$uname', '$msg')");
$result1 = mysql_query("SELECT * FROM logs ORDER by id DESC");
while ($extract = mysql_fetch_array($result1)) {
echo "<span class = 'uname'>".$extract['username'].
"</span>: <span class = 'msg'> ".$extract['msg'].
"</span><br/>";
}
?>
<?php $con=mysql_connect('localhost',
'root',
'');
mysql_select_db('chatbox',
$con);
$result1=mysql_query("SELECT * FROM logs ORDER by id DESC");
while($extract=mysql_fetch_array($result1)) {
echo"<span class = 'uname'>" . $extract['username'] ."</span>: <span class = 'msg'> " . $extract['msg'] ."</span><br/>";
}
?>
<?php ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<style>
* {
margin: 0;
}
body {
padding-right: 250px;
padding-left: 250px;
margin: 0;
background-color: darkkhaki;
}
textarea {
resize: none;
width: 100%;
height: 300px;
background-color: #efefef;
}
a {
background-color: cadetblue;
padding: 15px 25px 15px 25px;
text-decoration: none;
color: white;
}
a:hover {
background-color: chartreuse;
}
</style>
</head>
<body>
<form name="form1">
Enter your Username
<input type="text" name="uname">
<br/>Enter your Message
<br/>
<textarea name="msg"></textarea>
<br/>
<br/>
Send
<br/>
<br/>
<div id="chatlogs">
Loading Chat...
</div>
</form>
<script>
function submitChat() {
if (form1.uname.value == '' || form1.msg.value == '') {
alert('Please Input Username and Message');
return;
}
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'insert.php?uname' + uname + '&msg=' + msg, true);
xmlhttp.send();
}
</script>
</body>
</html>
. Feel free to point out the mistakes.
Replace
insert.php?uname
with
insert.php?uname=
Updated Code:
xmlhttp.open('GET', 'insert.php?uname=' + uname + '&msg=' + msg, true);
You are not inserting uname

Login index form is not working with login.php if i use header() function

I am beginner in php.
I am trying to make a login form(index1.php).
It works fine if i redirect it to login.php using "action" attribute in form tag.
But i also want some validations on same index form.So, i am redirecting it to "login.php" using header function and not in "action" attribute.
No matter if i enter correct username and password or not, it is giving me errors of invalid variables '$username' and '$password' while executing the last else too of login.php(//that user doesnt exist).
Please help me in knowing whats wrong with my code and what should i do to make it run with login.php?
Here is the code of index1.php
<!DOCTYPE HTML>
<html>
<head><br>
<style>
.error {color: #FF0000;}
</style>
</head>
<body style="font-family: verdana, sans-serif;";>
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
<br>
<?php
$username=$password="";
$Err="";
if($_SERVER['REQUEST_METHOD']== "POST")
{
$valid = true;
if ((empty($_POST["username"])) || (empty($_POST["password"])))
{
$Err = "Please Enter your username and password";
$valid = false;
}
else
{
$username = test_input($_POST["username"]);
$password = test_input($_POST["password"]);
}
if($valid)
{
header("location:login.php");
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<span class="error"><?php echo $Err; ?></span>
<h2>Login</h2>
<form action="menubar.php?page=index1" method="post">
<font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
Password: <input type="password" name="password" style="padding: 4px;"/><p>
<input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
</form>
<h5> No Account?Register!</h5>
</div>
</body>
</html>
And here is the code of login.php.
<?php
session_start();
$username=$_POST["username"];
$password=$_POST["password"];
$message[]="Fill up both username and password";
$connect=mysql_connect("localhost","root","") or die("Couldnt connect to Database");
mysql_select_db("login") or die("Couldnt find Database");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!==0)//username exists in database
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword)//valid username and password
{
$_SESSION['username'] = $username;
header("Location: menubar.php?page=home");
}
else//incorrect password or username
die("incorrect password or username");
}
else//that user doesnt exit
die("that user doesnt exit");//
?>
Okay, Now i used 'sqli' instead
Here is that updated login.php code
<?php
session_start();
$username=$_POST["username"];
$password=$_POST["password"];
$message[]="Fill up both username and password";
$connect=mysqli_connect("localhost","root","") or die("Couldnt connect to Database");
mysqli_select_db($connect,'login') or die("Couldnt find Database");
$query = mysqli_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysqli_num_rows($query);
if($numrows!==0)//username exists in database
{
while($row = mysqli_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword)//valid username and password
{
$_SESSION['username'] = $username;
header("Location: menubar.php?page=home");
}
else//incorrect password or username
die("incorrect password or username");
}
else//that user doesnt exit
die("that user doesnt exit");//
?>
Now after updating i am not getting errors of invalid variables .
But it still not going on correctly.No matter whether i enter correct username and password or not, it is executing the innermost if i.e. (//valid username and password)
Thanks....
As already suggested, put all your PHP code before any HTML output
You are not passing the POST variables with the header() function, you can either use sessions or POST to the same page
So your code would be something like this
<?php
$username=$password="";
$Err="";
if($_SERVER['REQUEST_METHOD']== "POST")
{
$valid = true;
if ((empty($_POST["username"])) || (empty($_POST["password"])))
{
$Err = "Please Enter your username and password";
$valid = false;
}
else
{
$username = test_input($_POST["username"]);
$password = test_input($_POST["password"]);
}
if($valid)
{
include("login.php");
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head><br>
<style>
.error {color: #FF0000;}
</style>
</head>
<body style="font-family: verdana, sans-serif;";>
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
<br>
<span class="error"><?php echo $Err; ?></span>
<h2>Login</h2>
<form action="menubar.php?page=index1" method="post">
<font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
Password: <input type="password" name="password" style="padding: 4px;"/><p>
<input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
</form>
<h5> No Account?Register!</h5>
</div>
</body>
</html>
The problem in your code is in login.php, $_POST["username"] and $_POST["password"] was never been set so it the best thing you could do is not to use header and just use require_once
<!DOCTYPE HTML>
<html>
<head><br>
<style>
.error {color: #FF0000;}
</style>
</head>
<body style="font-family: verdana, sans-serif;";>
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
<br>
<?php
$username=$password="";
$Err="";
if($_SERVER['REQUEST_METHOD']== "POST"){
$valid = true;
if ((empty($_POST["username"])) || (empty($_POST["password"]))){
$Err = "Please Enter your username and password";
$valid = false;
}else{
$username = test_input($_POST["username"]);
$password = test_input($_POST["password"]);
}
if($valid)
{
require_once('login.php');
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<span class="error"><?php echo $Err; ?></span>
<h2>Login</h2>
<form action="menubar.php?page=index1" method="post">
<font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
Password: <input type="password" name="password" style="padding: 4px;"/><p>
<input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
</form>
<h5> No Account?Register!</h5>
</div>
</body>
</html>
It is very important to note that you should have not sent any output to the client before setting the header-
header("Location: menubar.php?page=home");//or login.php
So before sending any data validate your data and set the header, if invalid data else send the normal data.
Update: Below is complete tested code
index1.php
<?php session_start();?>
<!DOCTYPE HTML>
<html>
<head><br>
<style>
.error {color: #FF0000;}
</style>
</head>
<body style="font-family: verdana, sans-serif;";>
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
<br>
<?php if(isset($_SESSION['message'])){ echo "<span class='error'>".$_SESSION['message']."</span>"; $_SESSION['message']=null;}?>
<h2>Login</h2>
<form action="login.php" method="post">
<font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
Password: <input type="password" name="password" style="padding: 4px;"/><p>
<input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
</form>
<h5> No Account?Register!</h5>
</div>
</body>
</html>
login.php
<?php
session_start();
$username=$password="";
$Err="";
if($_SERVER['REQUEST_METHOD']== "POST")
{
$valid = true;
if ((empty($_POST["username"])) || (empty($_POST["password"])))
{
$Err = "Please Enter your username and password";
$valid = false;
}
else
{
$username = test_input($_POST["username"]);
$password = test_input($_POST["password"]);
}
if($valid) {
$valid = false;//reset $valid value to validate for Database test
//$username=$_POST["username"];
//$password=$_POST["password"];
//$message[]="Fill up both username and password";
$connect=mysqli_connect("localhost","root","") or die("Couldnt connect to Database");
mysqli_select_db($connect,'login') or die("Couldnt find Database");
//Note: mysqi_query() returns results of query
$result = mysqli_query($connect, "SELECT * FROM users WHERE username='$username'");//update here pass the $connect parameter
$numrows = mysqli_num_rows($result);//change here
if($numrows!==0)//username exists in database
{
$dbusername = null;//move it up for visibility after while block
$dbpassword = null;
while($row = mysqli_fetch_assoc($result))//Note here pass the result
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username == $dbusername&&$password==$dbpassword)//valid username and password
{
$_SESSION['username'] = $username;
header("Location: menubar.php?page=home");//the landing page
die();
}
else{
//incorrect password or username
$Err = "incorrect password or username";
$valid = false;
}
}
else {
//that user doesnt exit
$Err = "that user doesnt exit";
$valid = false;
}
//header("location:index.php");
}
if(!$valid) {
$_SESSION['message'] = $Err;//Put the message in $_SESSION variable
header("location:index1.php");
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
menubar.php
<?php
session_start();
$page=isset($_GET["page"])?$_GET["page"]:"";
if(isset($page)) {
header("location: ".$page.".php");
} else {
header("location: 404.php");
}
?>
That is because you have an output:
?>
<?php
results in blank line output.
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.
also after header('location: index.php'); add exit(); if you have any other scripts bellow.
Also move your redirect header after the last if.

How do I dipslay the attributes of the tables from a lists of database tables when I click that table? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<td>
<p>
<div class="column">
<p><b>SELECT A DATABASE</b></p>
<p> <?php echo$this->form->getInput('Database_1');
include "db1.js.php" ?>
</div>
</td>
<td>
<p>
<div class="column" id="tbDiv">
<p><b>TABLES</b></p>
<select name="List of Tables" size="25" multiple id='table1' name='table1' title='List of Tables' class='inputbox'>
<option >Tables will be listed here...</option></select>
</div><p>
</td>
This the code in displaying the tables in a list from a selected database. I want to display the attributes of the table when i click it.
Try this using ajax and php
<?php
$db = new PDO('mysql:host=localhost;dbname=mysql','root','');
$dbs = $db->query( 'SHOW DATABASES' );
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
li:hover{
cursor: pointer;
}
#list{
float: left;
width: 30%;
}
#table{
float: right;
width: 68%;
}
#main{
width: 70%;
margin: 0 auto;
}
table,th,td{
border: 1px solid #000;
}
th{
width: 120px;
background-color: #000;
color: #fff;
text-transform: capitalize;
}
table {
border-collapse: collapse;
}
</style>
</head>
<body>
<div id="main">
<div id="list">
<select id="dbase" onchange="getTables(this.value)">
<option>Select databse</option>
<?php
while( ( $db = $dbs->fetchColumn( 0 ) ) !== false )
{
echo '<option>',$db,'</option>';
}
?>
</select>
<!-- displaying dropdown ************* -->
<option id="bulk" onchange="drop(this.value)"></option>
</div>
<div id="table"></div>
</div>
<script type="text/javascript">
//*************update for displaying dropdown menu *******
function drop(table){
var table = table;
var db = dbase.value;
var data = new XMLHttpRequest();
data.open("POST","list.php");
data.onreadystatechange = function(){
if(data.readyState === 4 && data.status === 200){
document.getElementById('table').innerHTML = data.responseText;
}
}
data.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
data.send('table='+table+'&dbase='+db);
}
//***********end of update **********
function getTables(table){
var data = new XMLHttpRequest();
data.open("POST","get_tables.php");
data.onreadystatechange = function(){
if(data.readyState === 4 && data.status === 200){
document.getElementById('bulk').innerHTML = data.responseText;
}
}
data.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
data.send('table='+table);
}
</script>
</body>
</html>
create get_tables.php
<?php
$dbname = $_POST['table'];
$db = new PDO("mysql:host=localhost;dbname=$dbname","root","");
$query = $db->prepare('show tables');
$query->execute();
$tabe_in = 'Tables_in_'.$dbname;
$results = $query->fetch(PDO::FETCH_ASSOC);
while ($results != null) {
// change <li> to <option> here **********
echo '<option>',$results[$tabe_in],'</option>';
$results = $query->fetch(PDO::FETCH_ASSOC);
}
?>
and res.php
<?php
$table = $_POST['table'];
$dbname = $_POST['dbase'];
$sql = "SHOW COLUMNS FROM $table";
$db = new PDO("mysql:host=localhost;dbname=$dbname","root","");
$table_headers = array();
$results = $db->prepare($sql);
$results->execute();
$res = $results->fetch();
?>
<table>
<tr>
<?php
while ($res != null) {
echo '<th>',$res['Field'],'</th>';
$table_headers[] = $res['Field'];
$res = $results->fetch();
}
?>
</tr>
<?php
$query = $db->prepare("SELECT * FROM $table");
$query->execute();
$rs = $query->fetchAll();
foreach ($rs as $value) {
echo '<tr>';
foreach ($table_headers as $val) {
echo '<td>',$value[$val],'</td>';
}
echo '</tr>';
}
?>

PHP: global variable not being stored?

It turns out this has nothing to do with global variables (sorry discussed in another post).
I was trying to keep all the code on one page (self-processing), but I'm pretty sure it's not possible. Arranging the following code outlined in the answer below, on the same page, does not work. Figures.
*edited to add the whole script minus the CSS (unnecessary).
<!DOCTYPE html>
<head>
<title>Inventory Tables</title>
</head>
<style></style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<?php //Menu for table selection
ini_set('display_errors',1); error_reporting(E_ALL);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<div id="select">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" value="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<!-- Code for Database Tables and Actions -->
<?php //inventory mysql tables
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['value'])) {
$thisTable = $_POST['value'];
global $thisTable;
ini_set('display_errors',1); error_reporting(E_ALL);
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
$columns = array();
while ($column = $resultColumns->fetch_row()){
$columns[] = $column[0];
}
echo "<div id=\"table\"><table class=\"CSSTableGenerator\" >\n";
$count = count($columns);
$insertColumns = array();
for ($pointer = 1 ; $pointer < $count ; ++$pointer) {
$insertColumns[] = $columns[$pointer];
}
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<th scope=\"col\" bgcolor=\"#efefef\">";
echo $columns[$pointer];
echo "</th>";
}
echo "<th>ACTIONS</td>";
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
$rows = $resultRows->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$resultRows->data_seek($j);
$row = $resultRows->fetch_array(MYSQLI_NUM);
$count = count($row);
echo "<tr>";
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<td>";
echo $row[$pointer];
echo "</td>";
}
?>
<td>
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="edit" name="edit">
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="delete" name="delete">
</td>
</tr>
<?php
}
echo "</table></div>"; //end table, end content
$connection->close();
}
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<?php for ($pointer = 1 ; $pointer < $count ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="go">
</td>
</form>
</table>
</div> <!-- end form, end table, end content -->
<?php
global $thisTable;
echo $thisTable;
if (isset($_POST['control'])) {
global $thisTable;
echo $thisTable;
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
//array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
print_r($columnsString);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode(" ", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = str_replace(" ", "', '", $valuesString);
$valuesString = substr($valuesString, 3);
print_r($valuesString);
/*
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
$connection->close();
*/
}
?>
</div> <!-- End #content -->
</body>
</html>
After 20 hours or so I'm still not sure if this possible to do all on the same page. But this solution works...
Page one:
<!DOCTYPE html>
<head>
<title>Interactive Resource Center Inventory</title>
<meta charset="UTF-8">
</head>
<script src="../_js/jquery.min.js"></script>
<script src="../_js/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$('input[type=submit]')
prop('disabled',true);
});//end submit
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>Column: <input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});//end ready
</script>
<style>
#table {
margin-top:2px;
}
#formTable {
width:100%;
margin:0px;padding:0px;
border:1px solid #000000;
border-bottom:none;
border-left:none;
border-right:none;
}
#formTable td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
#formTable input[type="text"]{
width:95%;
}
.CSSTableGenerator {
margin:0px;padding:0px;
width:100%;
border:1px solid #000000;
border-top:none;
border-right:none;
border-left:none;
}
.CSSTableGenerator table{
width:100%;
height:100%;
margin:0px;padding:0px;
}
.CSSTableGenerator tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator tr:nth-child(even) { background-color:#ffffff; }
.CSSTableGenerator th{
border:1px solid #000000;
border-width:0px 1px 1px 0px;
width:100px;
}
.CSSTableGenerator td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
.CSSTableGenerator tr:last-child td{
border-width:0px 1px 0px 0px;
}
.CSSTableGenerator tr td:last-child{
border-width:0px 0px 1px 0px;
}
.CSSTableGenerator tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
border:0px solid #000000;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:arial;
font-weight:bold;
color:#000000;
margin-top:-2px;
</style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require("IRCinventoryfunctions.php");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
$_SESSION['value'] = $_POST['value'];
$thisTable = $_SESSION['value'];
var_dump($_SESSION);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<div id="select">
<form action="http://localhost:8888/IRC/IRCinventoryhometest.php" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" name="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$thisTable = "OUTGOING";
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
$connection->close();
} else {
if(isset($_POST['value'])) {
$thisTable = $_POST['value'];
}
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="http://localhost:8888/IRC/IRCprocessinventory.php" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<td></td>
<?php for ($pointer = 2 ; $pointer < $countColumnsGlobal ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div> <!-- end table -->
<?php
}
?>
</div> <!-- End #content -->
</body>
</html>
Page 2:
<?php
require_once 'IRCinventoryconfig.php';
ini_set('display_errors',1); error_reporting(E_ALL);
session_start();
if(isset($_SESSION['value'])) {
$thisTable = $_SESSION['value'];
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode("','", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = substr($valuesString, 3);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
else echo "Successful entry";
$connection->close();
}
?>

How to display data from mysql using angular.js PHP?

How to print data recieved from mysql using angular.js PHP.
I want to know how to connect with mysql and angular.js
I tried with node.js mongodb. but wants to know about php,mysql,angular.js
Hi Can you check following sample code
your HTMLpage :
<html ng-app>
<head>
<title>AngularJs Post Example: DevZone.co.in </title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<style>
#dv1{
border:1px solid #DBDCE9; margin-left:auto;
margin-right:auto;width:220px;
border-radius:7px;padding: 25px;
}
.info{
border: 1px solid;margin: 10px 0px;
padding:10px;color: #00529B;
background-color: #BDE5F8;list-style: none;
}
.err{
border: 1px solid; margin: 10px 0px;
padding:10px; color: #D8000C;
background-color: #FFBABA; list-style: none;
}
</style>
</head>
<body>
<div id='dv1'>
<form ng-controller="FrmController">
<ul>
<li class="err" ng-repeat="error in errors"> {{ error}} </li>
</ul>
<ul>
<li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
</ul>
<h2>Sigup Form</h2>
<div>
<label>Name</label>
<input type="text" ng-model="username" placeholder="User Name" style='margin-left: 22px;'>
</div>
<div>
<label>Email</label>
<input type="text" ng-model="useremail" placeholder="Email" style='margin-left: 22px;'>
</div>
<div>
<label>Password</label>
<input type="password" ng-model="userpassword" placeholder="Password">
</div>
<button ng-click='SignUp();' style='margin-left: 63px;margin-top:10px'>SignUp</button>
</form>
</div>
<script type="text/javascript">
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.SignUp = function() {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http.post('post_es.php', {'uname': $scope.username, 'pswd': $scope.userpassword, 'email': $scope.useremail}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
}
}
</script>
<a href='http://devzone.co.in'>Devzone.co.in</a>
</body>
</html>
////////////////////////////////////////////////////////////////////////
Your php code
<?php
$data = json_decode(file_get_contents("php://input"));
$usrname = mysql_real_escape_string($data->uname);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('test', $con);
$qry_em = 'select count(*) as cnt from users where email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if ($res['cnt'] == 0) {
$qry = 'INSERT INTO users (name,pass,email) values ("' . $usrname . '","' . $upswd . '","' . $uemail . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
Please checkthe above code you will be understand how it will work. If any problem you are facing just tell me here in comment line

Categories