Fill table from input from mysql - php

I have an input, in which a code is entered and filled the table below with information from mysql optenida, the question is that I want every time a code is entered, the table all the data is added (without deleting the previous ). I got the idea to do with Ajax, but do not know where to start. So you see there is an easier way that I'm not seeing (finding on google). I do not like to add this data to a table, I would like it to be temporarily (until the table is confirmed, will be added to the db).
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table>
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require ("conectar.php");
$_SESSION["codigo"] = $_POST["input_codigo"];
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
?>
</table>
</body>
</html>

Maybe something like this i write below.
Added jQuery and Ajax request to get the data and then add it to the table.
Changed the PHP a little so that the main HTML is not returned if it is and AJAX request.
Hope it works for you (i didnt test it).
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
$bAjaxRequest = false;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$bAjaxRequest = true;
}
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="post" id="frmQuery" name="frmQuery">
<input type="text" name="input_codigo" id="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table id="tblData" name="tblData">
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
} // end if(!$bAjaxRequest) {
// we are always going to return the TR's or ""
require ("conectar.php");
// ALWAYS, BUT ALWAYS VERIFY/VALIDATE USER INPUT!!!
$_SESSION["codigo"] = mysql_real_escape_string($_POST["input_codigo"]); // for example
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) { ?>
</table>
<script type="text/javascript">
function loadData(codigo) {
$.post( "index.php", { input_codigo: codigo }, function( data ) {
$("#tblData").append(data);
});
}
$(function() {
// jQuery POST are never cached, but if you change to GET you'll need this next line
//$.ajaxSetup ({ cache: false });
$("#frmQuery").submit(function(e) {
e.preventDefault();
loadData($("#input_codigo").val());
});
});
</script>
</body>
</html>
<?php
}
?>

Related

I got a problem with select option and value

I try to keep the value from selected options after the button is clicked.
For now, I have done this with my inputs(range,text) and it's working but I can't figure how to do this with my select option.
ADDITIONAL THINGS(you have to create them to run it)
c13ustawienia.php
<?php
$serwer='localhost';
$uzytk='root';
$haslo='';
$baza='komis';
?>
c13dane.txt
1993|Volkswagen|Passat|19000
1973|Opel|Blitz|12000
1997|Volkswagen|Passat|17000
2010|Mercedes|M5|29000
2001|Volkswagen|Passat|29000
1990|Volkswagen|Passat|23000
2018|Tesla|Super|129000
2018|sla|Super|9000
1992|Volkswagen|Passat|10000
2006|Audi|B9|74000
2009|Volkswagen|Passat|89000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Baza</title>
<style>
table {border-collapse: collapse;}
td,th {border: 1px blue solid;}
th {background-color: azure;}
.id {width: 20px; text-align: center;}
.mar {width: 90px;}
.mod {width: 70px;}
.rok {width: 40px; text-align: right;}
.cena {width: 50px; text-align: right;}
.zolty {background-color: yellow;}
.pomar {background-color:orange;}
[type=text] {width:60px;}
header {height: 60px; background-color:greenyellow;}
header>img {height: 75%; text-align: center;}
nav {height: 400px; width: 30%; background-color:khaki;
float: left;}
main {height: 400px; width: 70%; background-color:moccasin;
float: left;}
footer {height: 40px; background-color: powderblue;
clear: both; text-align: center; color:blue;}
</style>
<script>
function wartosc() {
min=document.getElementById('cmin');
max=document.getElementById('cmax');
wmin=document.getElementById('wmin');
wmax=document.getElementById('wmax');
minint=parseInt(min.value);
maxint=parseInt(max.value);
if(maxint<minint)
maxint=minint+1;
wmin.value=minint;
min.value=minint;
wmax.value=maxint;
max.value=maxint;
}
</script>
</head>
<body>
<?php
function tworz_baze() {
require('c13ustawienia.php');
$link=mysqli_connect($serwer, $uzytk, $haslo);
mysqli_query($link, "DROP DATABASE $baza");
mysqli_query($link, "CREATE DATABASE $baza");
mysqli_query($link, "USE $baza");
mysqli_query($link, "CREATE TABLE auta (
ID int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
marka varchar(20),
model varchar(25),
rok int(4),
cena double)");
return $link;
} // tworz_baze()
function czytajdane($plik) {
$f=fopen($plik, 'r');
while(!feof($f)) {
$linia=rtrim(fgets($f));
if(strlen($linia)>5)
$tab[]=explode('|', $linia);
}
return $tab;
} // czytajdane($plik)
function dobazy($link, $tablica) {
foreach ($tablica as $sam) {
list($rok, $mar, $mod, $cena)=$sam;
mysqli_query($link, "INSERT INTO auta VALUES
(NULL, '$mar', '$mod', $rok, $cena)");
}
} // dobazy($link, $tablica)
function pisz($li, $marka, $cenamin, $cenamax) {
echo "<h3>Wybrano:<br>marka: $marka<br>
zakres cen: $cenamin - $cenamax zł</h3>";
echo "<table>
<tr><th>id</th><th>marka</th><th>model</th>
<th>rok</th><th>cena</th></tr>";
$wyn=mysqli_query($li, "SELECT * FROM auta WHERE
marka='$marka' AND cena>=$cenamin AND cena<=$cenamax");
$licznik=FALSE;
while($wiersz=mysqli_fetch_array($wyn)) {
list($id, $mar, $mod, $rok, $cena)=$wiersz;
$kolor = $licznik ? 'zolty' : 'pomar';
echo "<tr class=\"$kolor\"><th class=\"id\">$id</td>
<td class=\"mar\">$mar</td>
<td class=\"mod\">$mod</td>
<td class=\"rok\">$rok</td>
<td class=\"cena\">$cena</td></tr>";
$licznik=!$licznik;
}
echo '</table>';
mysqli_close($li);
} // pisz($li, $model, $cenamax)
function filtry() {
if(isset($_GET['cmin']))
$tab['cmin']=$_GET['cmin'];
else
$tab['cmin']=0;
if(isset($_GET['cmax']))
$tab['cmax']=$_GET['cmax'];
else
$tab['cmax']=CENAMAKS;
if(isset($_GET['marka']))
$tab['marka']=$_GET['marka'];
else
$tab['marka']='Volkswagen';
return $tab;
} // filtry()
function lista($link) {
$w=mysqli_query($link, "SELECT DISTINCT marka
from auta ORDER BY marka");
while($m=mysqli_fetch_array($w))
echo '<option value="'.$m['marka'].'">'
.$m['marka'].'</option>';
// $x=$m['marka'];
// "<option value=\"$x\">....
} // lista($link)
?>
<header>
<img src="auto.png" alt="auto">
<span>Komis samochodowy</span>
</header>
<nav>
<h3>Filtry:</h3>
<form action="c41.php" method="GET">
Cena:<br>
od: <input type="range" name="cmin" id="cmin"
min="0" max="<?php echo CENAMAKS ?>" value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
do :<input type="range" name="cmax" id="cmax"
min="0" max="<?php echo CENAMAKS ?>"
value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
<input type="text" name="wmin" id="wmin" disabled
value="<?php echo $tf['cenamin'];?>"
> -
<input type="text" name="wmax" id="wmax" disabled
value="<?php echo $tf['cenamax'];?>"
><br>
<select name="marka" id="marka">
<?php lista($li); ?>
</select>
<input type="submit" value="Filtruj">
<input type="reset" value="Czyść">
</form>
</nav>
<main>
<?php pisz($li, $tf['marka'], $tf['cmin'], $tf['cmax']); ?>
</main>
<footer>
Adam Kowal ©
</footer>
</body>
</html>
To make inputs work I have giving them variable of function and pointed right key of database to have what I want, but i have no clue how to make it work with select option
frame of code that gives me what i want in inputs: value="<?php echo $tf['cenamin'];?>"
Change your code with the following:
First add a new parameter to the "lista" function to be able to mark the selected value, e.g.
function lista($link, $selected = "default") {
// function code here
}
Secondly, modify the function to respect the passed value and match it to the value gotten from the database:
while($m=mysqli_fetch_array($w)) {
$status = "";
if ($selected == $m['marka']) $status = "selected";
echo '<option '.$selected.' value="'.$m['marka'].'">' .$m['marka'].'</option>';
}
Thirdly, pass the selected value to the function in your code, e.g.:
<?php lista($li, $_GET['marka']); ?>
NB! You should NOT use your current code in any production environments: it includes several SQL injections and isn't built up by best practises (e.g. separating html from the program code etc).

Convert eBay Link Generator results into bitly.com link

I managed a small PHP script that takes the eBay product searched and converts it into promote eBay link.
It goes like this:
user searches for example: ocz vertex
clicks on "Submit" and gets the results in following format
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz
vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
(Can't fix that space in the link generated between ocz and vertex words)
Now, the result is nice, but I want to shorten it via bitly.com account using their API.
Basicly I want it to generate and convert the full eBay link results into small bitly.com link (http://ebay.to/2scU91k for example) and to see that link on my bitly account.
The process would go like this:
User search for term like ocz vertex
click on "Submit"
get the ebay.to short link (while the real process is in background,
converts to rover.ebay.com address and then to ebay.to using my
bitly.com credentials)
I found that and that and especially that, but didn't understand how do I implement the results as a new bitly convert.
Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
body{
margin:0px;
font-size:0.7em;
font-family:trebuchet ms;
color:#222;
}
#mainContainer{
width:840px;
margin:5px;
}
table,tr,td{
vertical-align:top;
}
.textInput{
width:300px;
}
html{
margin:0px;
}
.formButton{
width:75px;
}
textarea,input,select{
font-family:helvetica;
}
i{
font-size:0.9em;
}
</style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>
</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
</div>
</td><td valign="top">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
URL<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url" size="20">
<br>
<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name=array($url);
foreach ($name as $name)
{
if (ereg("^\.",$url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\<", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\[", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\'", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\#", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\`", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (!strlen($url)) {
echo "<br><center><font color=\"red\">Empty Field.</center>";
Die();
}
if (strlen($url) > 100) {
echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
Die();
}
}
?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=<?php echo $url ?>&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
</textarea>
<br>
</form>
<?php
}
?>
</body>
</html>
See on live: Ebay link Generator
I built a small solution that works without external libraries. It essentially boils down to this:
Acquire an API key from the "Register an application" dashboard or an oauth token from the oauth API
Make the request to the /v3/shorten API endpoint with your token and URL
First step: Get the token
You only need to do this once. Bitly's documentation lists a few examples how you can do it using curl, I think that is the easiest way. You could also do it with PHP. Simply make this POST request (taken from here):
curl -u "username:password" -X POST "https://api-ssl.bitly.com/oauth/access_token"
The result is something like this:
e663e30818201d28dd07803e57333bed4f15803a
That is your token.
Second step: Make the request
Insert the token and url-encoded URL into the HTTP request to the /v3/shorten endpoint:
<?php
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz%20vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg"
$token = "e663e30818201d28dd07803e57333bed4f15803a"; // change this
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url)."";
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
echo $short_url;
?>
The result of the API call is JSON and needs to be decoded. An example is in the documentation. This code example does not take into consideration API timeouts or other errors that might occur (such as token expiry, which is currently not an issue).
The complete code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
body{
margin:0px;
font-size:0.7em;
font-family:trebuchet ms;
color:#222;
}
#mainContainer{
width:840px;
margin:5px;
}
table,tr,td{
vertical-align:top;
}
.textInput{
width:300px;
}
html{
margin:0px;
}
.formButton{
width:75px;
}
textarea,input,select{
font-family:helvetica;
}
i{
font-size:0.9em;
}
</style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>
</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
</div>
</td><td valign="top">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
Insert keywords:<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url" size="20">
<br>
<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name = array($url);
foreach ($name as $name) {
if (preg_match("/^[\.\<\[#`]/",$url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (!strlen($url)) {
echo "<br><center><font color=\"red\">Empty Field.</center>";
Die();
}
if (strlen($url) > 100) {
echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
Die();
}
}
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=".urlencode($url)."&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg";
$token = "e663e30818201d28dd07803e57333bed4f15803a";
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url);
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
<?php echo $short_url; ?>
</textarea>
<br>
</form>
<?php
}
?>
</body>
</html>
Note: I changed your ereg calls to preg_match for compatibility with PHP7 and shortened the ifs with a regular expression. I also used urlencode($url) so that spaces won't break the link.

query is not running in php

Hi there i am trying to create a screen in php.
in which i select scenario and the screen displayed accordingly.
but i am stuck in a simple problem that my simple select query is not working
which is
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery) or die("adfasdf");
in same code if change the table name it just work fine, also this table is created in the db as well with the same name i have shared.
here is my complete code.
<?php
include "include/conn.php";
include "include/session.php";
if(isset($_SESSION['logged_user']) && $_SESSION['logged_user'] != '99999'){
header('location: login.php');
}
$query = mysql_query("select curdate() as todayDate");
$show = mysql_fetch_array($query);
if(isset($show)){
$todayDate= $show['todayDate'];
}
$group[] = array();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta Content="no-cache, no-store, must-revalidate" http-Equiv="Cache-Control" />
<meta Content="no-cache" http-Equiv="Pragma" />
<meta Content="0" http-Equiv="Expires" />
<link href="styles/style.css" type="text/css" rel="stylesheet" />
<link href="styles/popupstyle.css" type="text/css" rel="stylesheet" />
<link href="styles/ts.css" type="text/css" rel="stylesheet" />
<link href="styles/calendar.css" type="text/css" rel="stylesheet" />
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
font-size: 11px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body >
</body>
<select id='select_opt'>
<option> Select Assigment </option>
<option value="1"> assign quiz to all Employees </option>
<option value="2"> assign quiz to Sapcific Group </option>
<option value="3"> assign quiz to Sapcific Department </option>
<option value="4"> assign quiz to Sapcific Employee </option>
</select>
<!-- all Users -->
<div id='allUsers' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<select>
<option value=""> select Quiz</option>
</select>
<input type="submit" >
</form>
</div>
<!-- group -->
<div id='group' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>All <input type="checkbox"> </th>
<th>Group Name</th>
<th>Group Code</th>
</tr>
<?php
$group[] = array();
$groupQuery = "Select * from mcb_groups";
$query = mysql_query($groupQuery);
?>
<tr>
<?php if($query){
while($group = mysql_fetch_array($query)){
?>
<td><input type="checkbox" value="<?php echo $group['group_name']; ?>"></td>
<td><?php echo $group['group_name']; ?></td>
<td><?php echo $group['group_code']; ?></td>
</tr>
<?php }
} else{ echo "";} ?>
</table>
</form>
</div>
<!--
####################################
department
####################################
-->
<div id='Department' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>all <input type="checkbox"> </th>
<th>name</th>
<th>code</th>
<th>group</th>
</tr>
<tr>
<?php
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
?>
<td><input type="checkbox"></td>
<td>code</td>
<td>name</td>
<td>group</td>
</tr>
</table>
<input type="submit" >
</form>
</div>
<!--
####################################
Employee
####################################
-->
<div id='employee' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<label>employee id : </label><input type="text" >
<input type="submit" >
</form>
</div>
<script language="javascript" type="text/javascript">
var elem = document.getElementById("select_opt");
elem.onchange = function(){
console.log("yes i am running");
if( document.getElementById("select_opt").value == "1" ){
document.getElementById("allUsers").style.display = "Block";
document.getElementById("group").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "2" ){
document.getElementById("group").style.display = "Block";
document.getElementById("allUsers").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "3" ){
document.getElementById("Department").style.display = "block";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "4" ){
document.getElementById("employee").style.display = "block";
document.getElementById("Department").style.display = "none";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
}
else{
}
};
</script>
</
html>
regard,
Shafee jan
in same code if change the table name it just work fine
Then I would make sure you're connected to the right database. It's surprisingly common for developers to have multiple versions of their database, either on different MySQL instances or else on the same instance under a different schema name. Then they get mixed up, connecting to one database with MySQL Workbench while their app is connecting to a different database.
I would advise that you temporarily add a query to your page to run SHOW TABLES and then dump the result of that query to the log, to confirm that the mcb_department table is present in the database that your PHP script is connected to.
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
Where's your error checking? You need to check the return value of mysql_query() every time you run a query, so if there's a problem, you output the error message to your log. Only this way can you start to solve some of these problems.
$result = mysql_query($deptQuery);
if (!$result) {
trigger_error("Error in file " . __FILE__ . " near line " . __LINE__
. " for query $deptQuery: " . mysql_error());
die("Database error");
}
PS: The advice of some commenters that mysql_* functions are deprecated is true, but probably irrelevant to your question. Folks who focus on the API, when you have said the API is working, are just being pedantic.

editing CSS of PHP grid

I have an editable grid where I want to edit the CSS such that the textarea to show the maximum width, but somehow I can't increase the width of the text area.
My database has three columns:
ID
Name
Gossip
I'm retrieving everything and displaying it in an editable grid using PHP.
index.php code
<?php
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
die('Check the database connection again!');
}
$userQuery = 'SELECT Id,Name,Gossip FROM bollywood';
$stmt = $db->query($userQuery);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var textBefore = '';
$('#grid').find('td input').hover(function() {
textBefore = $(this).val();
$(this).focus();
}, function() {
var $field = $(this),
text = $field.val();
$(this).blur();
// Set back previous value if empty
if (text.length <= 0) {
$field.html(textBefore);
} else if (textBefore !== text) {
// Text has been changed make query
var value = {
'row': parseInt(getRowData($field)),
'column': parseInt($field.closest('tr').children().find(':input').index(this)),
'text': text
};
$.post('user.php', value)
.error(function() {
$('#message')
.html('Make sure you inserted correct data')
.fadeOut(3000)
.html('&nbsp');
$field.val(textBefore);
})
.success(function() {
$field.val(text);
});
} else {
$field.val(text);
}
});
// Get the id number from row
function getRowData($td) {
return $td.closest('tr').prop('class').match(/\d+/)[0];
}
});
</script>
<title></title>
</head>
<body>
<?php if ($stmt): ?>
<div id="grid">
<p id="message">Click on the field to Edit Data</p>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gossip</th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch_assoc()): ?>
<tr class="<?php echo $row['Id']; ?>">
<td><input type="text" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" value="<?php echo $row['Name']; ?>" /></td>
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p>No actors added yet</p>
<?php endif; ?>
</body>
</html>
user.php code
<?php
// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$fields = array('row', 'column', 'text');
$sqlFields = array('Id', 'Name', 'Gossip');
foreach ($fields as $field) {
if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
sendError('No correct data');
exit();
}
}
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
sendError('Connect error');
exit();
}
$userQuery = sprintf("UPDATE bollywood SET %s='%s' WHERE Id=%d",
$sqlFields[intval($_POST['column'])],
$db->real_escape_string($_POST['text']),
$db->real_escape_string(intval($_POST['row'])));
$stmt = $db->query($userQuery);
if (!$stmt) {
sendError('Update failed');
exit();
}
}
header('Location: index.php');
function sendError($message) {
header($_SERVER['SERVER_PROTOCOL'] .' 320 '. $message);
}
style.css code
body {
font: normal 14px Comic Sans, Comic Sans MS, cursive;
}
table {
width: 500px;
}
td, th {
border: 1px solid #d8d8bf;
}
th {
padding: 5px;
font: bold 14px Verdana, Arial, sans-serif;
}
td {
padding: 10px;
width: 200px;
}
td input {
margin: 0;
padding: 0;
// width:200px;
font: normal 14px sans-serif;
/** Less flicker when :focus adds the underline **/
border: 1px solid #fff;
}
td input:focus {
outline: 0;
border-bottom: 1px dashed #ddd !important;
}
#grid input {
// width: 200%;
}
You doing it wrong
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
Should be:
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
textarea is html tag name but not input type. so change this.
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
to
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
also add this css.
<style>
textarea {
resize: both;
width:700px;
}
</style>
also are you sure that you can get content using this.
<?php echo $row['Gossip']; ?>

javascript function not displaying correct page

i want to open a specific window according to a drop down selection, the function works fine on the first row of a set of data (pulling it from a database)
Since i don't know how many rows are going to come each time the script is running, i've created a loop and writting the function as many times as rows there are coming, having them named different.
The thing is that when i change the drop down from the first row, the correct window opens, for instance custom.php?id=1, but when i open the second one, if i select comunicarse from the list, it opens custom.php?id=2 (id=2 is the user's id)
Here is the code, and i really hope you can understand me....
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
table {
border-style:ridge;
border-width:1px solid;
border-collapse:collapse;
font-family:sans-serif;
font-size:12px;
width:100%;
}
table thead th, table.excel tbody th {
background:#CCCCCC;
border-style:ridge;
border-width:1;
text-align: center;
vertical-align:bottom;
}
table tbody th {
text-align:center;
}
table tbody td {
vertical-align:bottom;
}
table tbody td {
padding: 0 3px;
border: 1px solid 0000000;
}
table td {
padding: 0 3px;
border: 1px solid 0000000;
}
</style>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<?php
include("../../cons/dbinfo.php");
$busco_react = "SELECT *
FROM `envios_mercadolibre`
WHERE status != 'ENTREGADA' AND status != 'CANCELADA' AND aviso != 1";
$bus1 = mysql_query($busco_react);
while ($b1 = mysql_fetch_array($bus1)){
$para = $b1['id'];
echo '<script language="Javascript" type="text/javascript">
function ReactToChange'.$para.'()
{
if (document.getElementById("DropDownList").value === "custom")
{
window.open("custom.php?id='.$para.'")
}
else if (document.getElementById("DropDownList").value === "comunicarse")
{
window.open("comunicarse.php?id='.$para.'")
}
else if (document.getElementById("DropDownList").value === "esperando")
{
window.open("esperando.php?id='.$para.'")
}
else if (document.getElementById("DropDownList").value === "compro")
{
window.open("compro.php?id='.$para.'")
}
else {}
}
</script>';
}
?>
</head>
<body>
<table width = "2200px">
<tr><td colspan="3" align="center">Back to index</td></tr>
</table>
<br />
<?php
echo "<form method='post' action='sendemails.php'>";
echo "<table border='1' cellpading ='0' cellspacing ='0'>";
echo "<thead><tr><th>MAIL</th><th>Email Address</th><th>Content</th>
<th>Extra 1</th><th>Extra 2</th><th>Full Address</th><th>Full Name</th></tr>
</thead><tbody>";
$bus = "SELECT * FROM `envios_mercadolibre` WHERE status != 'ENTREGADA' AND status != 'CANCELADA' AND aviso != 1";
$bu = mysql_query($bus) or die("este");
while ($b = mysql_fetch_array($bu)){
$contenido = $b['contenido'];
$extra1 = $b['extra1'];
$extra2 = $b['extra2'];
$usuario_id = $b['usuario_id'];
$para1 = $b['id'];
$datosUsuario = "SELECT nombre, apellido, email from usuarios WHERE id = $usuario_id";
$datosU = mysql_query($datosUsuario) or die("foo");
while ($c = mysql_fetch_array($datosU)){
$nombre = $c['nombre'];
$apellido = $c['apellido'];
$email = $c['email'];
$todoelnombre = $nombre.", ".$apellido;
echo "<tr>
<td><select id='DropDownList' onchange='ReactToChange$para1()'>
<option value='later'>LATER</option>
<option value='comunicarse'>COMUNICARSE CON NOSOTROS</option>
<option value='esperando'>ESPERANDO CALIFICACION EN MERCADO LIBRE</option>
<option value='compro'>NO COMPRO</option>
<option value='custom'>CUSTOM</option>
</select></td>
<td>$email</td>
<td>$contenido</td>
<td>$extra1</td>
<td>$extra2</td>
<td>$todaladire</td>
<td>$todoelnombre
<input type='hidden' name ='datos-$para1' value ='$email' />
</td>
</tr>
";
}
}
echo "<tr><TD colspan ='7' align='center'><input type='submit' /></td></tr></table>";
?>
</div>
</body>
</html>
It's hard to tell an exact answer without seeing your database structure, but at first I would not create your javascript function inside the while loop, as it will make several functions. On the top of that you really do not need the first SELECT if you use a parameterized javascript function that you call later with the apropriate parameters.
I have modified your code, please take a look at a more effective javascript function and its calling below:
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
table {
border-style:ridge;
border-width:1px solid;
border-collapse:collapse;
font-family:sans-serif;
font-size:12px;
width:100%;
}
table thead th, table.excel tbody th {
background:#CCCCCC;
border-style:ridge;
border-width:1;
text-align: center;
vertical-align:bottom;
}
table tbody th {
text-align:center;
}
table tbody td {
vertical-align:bottom;
}
table tbody td {
padding: 0 3px;
border: 1px solid 0000000;
}
table td {
padding: 0 3px;
border: 1px solid 0000000;
}
</style>
<link rel="stylesheet" href="../css/style.css" type="text/css">
<script language="Javascript" type="text/javascript">
function ReactToChange(para,ptype)
{
window.open(ptype+".php?id="+para);
}
</script>
</head>
<body>
<table width = "2200px">
<tr><td colspan="3" align="center">Back to index</td></tr>
</table>
<br />
<?php
echo "<form method='post' action='sendemails.php'>";
echo "<table border='1' cellpading ='0' cellspacing ='0'>";
echo "<thead><tr><th>MAIL</th><th>Email Address</th><th>Content</th>
<th>Extra 1</th><th>Extra 2</th><th>Full Address</th><th>Full Name</th></tr>
</thead><tbody>";
$bus = "SELECT * FROM `envios_mercadolibre` WHERE status != 'ENTREGADA' AND status != 'CANCELADA' AND aviso != 1";
$bu = mysql_query($bus) or die("este");
while ($b = mysql_fetch_array($bu)){
$contenido = $b['contenido'];
$extra1 = $b['extra1'];
$extra2 = $b['extra2'];
$usuario_id = $b['usuario_id'];
$para1 = $b['id'];
$datosUsuario = "SELECT nombre, apellido, email from usuarios WHERE id = $usuario_id";
$datosU = mysql_query($datosUsuario) or die("foo");
while ($c = mysql_fetch_array($datosU)){
$nombre = $c['nombre'];
$apellido = $c['apellido'];
$email = $c['email'];
$todoelnombre = $nombre.", ".$apellido;
echo "<tr>
<td><select id='DropDownList' onchange='ReactToChange($para1,this.options[this.selectedIndex].value)'>
<option value='later'>LATER</option>
<option value='comunicarse'>COMUNICARSE CON NOSOTROS</option>
<option value='esperando'>ESPERANDO CALIFICACION EN MERCADO LIBRE</option>
<option value='compro'>NO COMPRO</option>
<option value='custom'>CUSTOM</option>
</select></td>
<td>$email</td>
<td>$contenido</td>
<td>$extra1</td>
<td>$extra2</td>
<td>$todaladire</td>
<td>$todoelnombre
<input type='hidden' name ='datos-$para1' value ='$email' />
</td>
</tr>
";
}
}
echo "<tr><TD colspan ='7' align='center'><input type='submit' /></td></tr></table>";
?>
</div>
</body>
</html>
instead of writing multiple function you can write
function ReactToChange(para)
{
//only call document.getElementById("DropDownList").value once - good programming practice
var dropdownvalue = document.getElementById("DropDownList").value;
if (dropdownvalue === "custom")
{
window.open("custom.php?id='"+para+"'")
}
else if (dropdownvalue === "comunicarse")
{
window.open("comunicarse.php?id='"+para+"'")
}
...
}
<select id='DropDownList' onchange='ReactToChange($para1)'>
<option value='later'>LATER</option>
...
</select>
Now your code is shorter because you have just one function to handle everything
Note that you are passing the "Id" as parameter
If you have thousands of records, you would have generated thousands of functions slowing the page down
Not sure whether .value will always work properly. Consider the following changes at this point in your code:
function ReactToChange'.$para.'()
{
var dropdown = document.getElementById('DropDownList'),
selectedValue = dropdown.options[dropdown.selectedIndex];
// now make all comparisons against selectedValue
// ...
if (selectedValue === 'comunicarse') {
window.open("comunicarse.php?id='.$para.'")
}
// ...
}

Categories