can't create automatic sql tables after first use - php

I'm new with PHP and SQL...
I'm trying to create new tables based on the url, but it's only working the first time I use it. After that, it's not possible.
Here is my PHP code:
if(isset($_GET['id'])){
$tabela = $_GET['tabela'];
$_GET['id'];
$criar = $tabela . $nivel . $page_id;
// Se clicar no botão 'confirmar', então ele faz o seguinte:
if(isset($_POST['submit'])){
$titulo = $_POST['titulo'];
$_FILES['imagem']['tmp_name'];
$texto = $_POST['texto'];
// Se um destes campos estiver vazio:
if($titulo=='' or $imagem=='' or $texto==''){
echo "Preencha todos os campos para o menu!";
exit(); }
// Se não houver campos vazios, ele faz: else {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "site";
// Ligação à base de dados:
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a ligação:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
// Se conseguir ligar-se à base de dados e criar uma nova tabela, ele insere os dados na nova tabela:
if ($conn->query($sql) === TRUE) {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Se inserir os dados na nova tabela, ele dá uma mensagem de sucesso:
if(mysql_query($insert_query)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "Erro: " . $insert_query . "<br>" . $conn->error;
}
}
// Caso ele não consiga criar uma nova tabela (porque já existe), ele insere os dados na tabela já existente:
else {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
if(mysql_query($sql)){
echo "sim!";
}
else {
echo "não!";
}
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Caso consiga inserir os dados na tabela já existente, dá uma mensagem de sucesso:
if(mysql_query($insert_query&&$sql)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "isto não está a correr bem!";
}
// Fecha a ligação à base de dados:
$conn->close();
} } }$nivel = $_GET['grupo']; $page_id =$imagem = $_FILES['imagem']['name']; $image_tmp =

What do you mean 1st time, 2nd time? Do you try to create another table with the same name you just have created? You'll get a table already exists error.
CREATE TABLE IF NOT EXISTS $criar
This explicitly tells MySql not to create the table if it exists, so if you pass the same query parameters to your php then it'll not be able to create the same table again.
Probably you could change it to:
$page_id = $_GET['id'];
$criar = $tabela . $nivel . $page_id;
And then pass a different id and/or different tabela every time.

this code looks behind the issue to me :
$tabela = $_GET['tabela'];
$_GET['id']; //this line looks odd
$criar = $tabela . $nivel . $page_id;
and maybe it's not creating new tables because you give the same $criar every time.

After hours of trying to solve this issue, i finally got good news! :) i was working in my local server (via xampp) and decided to put it online to check if something changes... and dont know why, but it works perfectly online and dont work with xampp! What a mess!! but its working!! thanks all for your help!! ;)

Related

Issue Updating date with Oracle and PHP

Im doing a Crud with PHP and Oracle, adding the info and deleting the info works fine. But Updating is not saving on the oracle database. Im sure that is something related to the DATE format, because I had the same project with other database and doesnt have any problem. Any guess, whats it happening?
<?php
require_once 'conexion.php';
$idautor = $_POST['ID_AUTOR'];
$nameautor = $_POST['NOMBRE_AUTOR'];
$bdate = date("m-d-Y", strtotime($_POST['FECHA_NACIMIENTO']));
$query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."', FECHA_NACIMIENTO ='".$bdate."' WHERE ID_AUTOR = '".$idautor."' ";
// $query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."' WHERE ID_AUTOR = '".$idautor."' ";
$statement = oci_parse($conexion,$query);
$r = oci_execute($statement,OCI_DEFAULT);
$res = oci_commit($conexion);
if ($res) {
// Mensaje si los datos cambian
echo "<script>alert('Los libros se actualizaron con exito'); window.location.href='sistema.php'</script>";
header('Location: sistema.php');
} else {
// Mensaje si los datos no cambian
echo "<script>alert('Los datos no se pudieron actualizar'); window.location.href='sistema.php'</script>";
// echo oci_error();
}
} else {
// si intenta acceder directamente a esta página, será redirigido a la página de índice
header('Location: sistema.php');
}
Your code is an open door for SQL-Injection. It should be like this:
$query = "UPDATE AUTOR SET
NOMBRE_AUTOR = :nameautor, FECHA_NACIMIENTO = TO_DATE(:bdate, 'YYYY-MM-DD')
WHERE ID_AUTOR = :idautor";
$statement = oci_parse($conexion, $query);
oci_bind_by_name($statement, ':nameautor', $nameautor, 1000, SQLT_CHR);
oci_bind_by_name($statement, ':bdate', date_format($bdate, 'Y-m-d'), 30, SQLT_CHR);
oci_bind_by_name($statement, ':idautor', $idautor, 100, SQLT_INT);
$r = oci_execute($statement, OCI_DEFAULT);
You have to use TO_DATE(...), because type like SQLT_DATE does not exist. Otherwise you rely on current session NLS_DATE_FORMAT which may change at any time.

How to save a file name in the MySQL database?

I have developed this code below to the user upload a file and save the name of this file in the database, to be able to access it later, the upload is done normally, it goes to the designated folder, but the name is not saved in the database, does anyone know what's wrong with the code? Especially below the move_uploaded_file, because so far it works, then it goes wrong.
<?php
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];
$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);
if (file_exists("uploads/$arq")) {
$a = 1;
while (file_exists("uploads/[$a]$arq")) {
$a++;
}
$arq = "[".$a."]".$arq;
}
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
$objDb = new db();
$link = $objDb->conecta_mysql();
$sql = "insert into arquivos (email_vol, nomearq) values ('$email', '$arq')";
if (mysqli_query($link, $sql)){
echo 'Plano de aula 1 enviado com sucesso!';
} else {
echo (mysqli_error($link));
echo 'Erro ao enviar o plano de aula!';
}
} else {
echo "Nenhum arquivo selecionado!";
}
}
?>
That is the code used to connect with the database:
class db {
//host
private $host = 'localhost';
//usuario
private $usuario = '111111';
//senha
private $senha = '11111111';
//banco de dados
private $database = 'dsfadsfasd';
public function conecta_mysql(){
//criar a conexão
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);
//ajustar a charser de cominicação entre a aplicação e o bd
mysqli_set_charset($con, 'utf8');
//verificar se houve erro de conexão
if (mysqli_connect_errno()) {
echo 'Erro ao tentar se conectar com o banco de dados'.mysqli_connect_error();
}
return $con;
}
}
?>
Don't have the privilege to comment right now but shouldn't this be like this plus you don't have a semicolon at the end of your sql script
$sql = "insert into arquivos (email_vol, nomearq) values ('" . $email . "', '"
.$arq . "');";
and also this
if (file_exists("uploads/" . $arq)) {
$a = 1;
while (file_exists("uploads/". $a . ".". $arq)) {
$a++;
}
$arq = $a.".".$arq;
}
with a full stop between your file number and name

Extract forex data from xlm with php and simplexml_load_file

<?php
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
print_r($xml);
?>
This script really works and the output is here:
http://sitoxte.com/test%20mercato/array.php
But what I want to do is put this data to MySQL tabs, I need some help because I want to store the data each minute.
So i Try:
json-to-mysql
but I think that array in xml variable is not adeguate.
I want create a for cicle
and create 69 table like this:
table 1 eur/usd
id - Bid - Ask - High - Low - Direction - Last - timestamp
1
2
3
4...
and so on
refresh mode is simple and I do in this way whit javascript:
<script>
setInterval(function () {}, 3000);
var myVar=setInterval(function(){myTimer()},10000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
location.reload();
}
</script>
connetion is simple too and is like this:
//Host:
$localhost="******";
//database
$mioblog=*******;
//Nome utente:
$username=********;
//Password:
$password=*******;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else
{
// notifica in caso di connessione attiva
echo "Connessione avvenuta con successo";
}
This depends on what you're using for your database, but assuming PDO, something like the below. If you need more details then look up a MySQL tutorial, but hopefully this gets you started and shows you how to traverse the XML.
foreach($xml->Rate as $rate) {
$query = "INSERT INTO tblrate (time, symbol, bid) VALUES (NOW(), :symbol, :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':symbol' => $rate->#attributes['Symbol'],
':bid' => $rate->Bid;
));
}
edit: If you only need one currency, something like this should work
foreach($xml->Rate as $rate) {
if($rate->#attributes['Symbol'] == 'EURUSD') {
$query = "INSERT INTO tblrate (time, bid) VALUES (NOW(), :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':bid' => $rate->Bid;
));
}
}
My friend Biagio help me to write code:
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
echo('$Symbol = '.$Symbol.'<br>');
echo('$Bid = '.$Bid.'<br>');
}
final code of php scrip that write in mysql tables every second forex data:
...
<body id="top">
<!-- <button onclick="myFunction()">Reload page</button> -->
<a id=demo> <a>
...
<?php
echo date("F j, Y, g:i a", time()).'<br>';
$html="";
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
//Host:
//echo('var_dump( $xml)<br>');
//var_dump( $xml);
//SimpleXMLElement
//Host:
$localhost="----";
//database
$mioblog=----;
//Nome utente:
$username=-----;
//Password:
$password=-----;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else {
// notifica in caso di connessione attiva
// echo "Connessione avvenuta con successo";
}
// sql to create table
// sql to create table
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
// sql to create table
/*
$sql = "CREATE TABLE $Symbol (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Bid VARCHAR(30) NOT NULL,
Ask VARCHAR(30) NOT NULL,
High VARCHAR(30) NOT NULL,
Low VARCHAR(30) NOT NULL,
Direction VARCHAR(30),
Last VARCHAR(30) NOT NULL,
reg_date TIMESTAMP
)";*/
$sql = "INSERT INTO $Symbol (Bid,Ask,High,Low,Direction,Last)
VALUES ('$Bid','$Ask',$High,$Low,$Direction,'$Last')";
if ($mysqli->query($sql) === TRUE) {
// echo "Inserito in table ".$Symbol." / bid=".$Bid." / ask=".$Ask."/ High=".$High."/ Low=".$Low."/ Direction=".$Direction."/ Last=".$Last."<br>";
} else {
echo "Error creating table: " . $mysqli->error;
}
// echo('$Symbol = '.$Symbol.'<br>');
//echo('$Bid = '.$Bid.'<br>');
//echo('$Ask = '.$Ask.'<br>');
//echo('$High = '.$High.'<br>');
//echo('$Low = '.$Low.'<br>');
// echo('$Direction = '.$Direction.'<br>');
// echo('$Last = '.$Last.'<br>');
}
$mysqli-->close();
?>
....

no database selected php/mysql

i have a trouble with this T_T this is a searching/consult script for cars parts
this is the php
<?php
if ($_POST['buscar'])
{
// Tomamos el valor ingresado
$buscar = $_POST['palabra'];
// Si está vacío, lo informamos, sino realizamos la búsqueda
if(empty($buscar))
{
echo "No se ha ingresado una cadena a buscar";
}else{
//Conexión a la base de datos
$servidor = "localhost"; //Nombre del servidor
$usuario = "root"; //Nombre de usuario en tu servidor
$password = "1234"; //Contraseña del usuario
$base = "db_maquinas"; //Nombre de la BD
$con = mysql_connect($servidor, $usuario, $password) or die("Error al conectarse al servidor");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$result = mysql_query($sql, $con);
// Tomamos el total de los resultados
if($result) { $total = mysql_num_rows($result); } else { die('Invalid query' . mysql_error($con)); }
echo "<table border = '1'> \n";
//Mostramos los nombres de las tablas
echo "<tr> \n";
while ($field = mysql_fetch_field($result)){
echo "<td>$field->name</td> \n";
}
echo "</tr> \n";
do {
echo "<tr> \n";
echo "<td>".$row["id"]."</td> \n";
echo "<td>".$row["descripcion"]."</td> \n";
echo "<td>".$row["cantidad"]."</td> \n";
echo "</tr> \n";
} while ($row = mysql_fetch_array($result));
echo "</table> \n";
echo "¡ No se ha encontrado ningún registro !";
}
}
?>
that when on the form i press "Send or Search" this send me to another page that says "NO DATABASE SELECTED"
I hope somebody can help me with that..
PD: i'm using a localhost DB with PhpMyAdmin i have items on tables, i verified tables not empty...
You select your database after you attempt to run queries. Place the code before you attempt to run queries:
mysql_select_db($base, $con) or die("Error al conectarse a la base de datos");
$sql= mysql_query("SELECT * FROM repuestos WHERE 'id','descripcion' LIKE '%$buscar%' ORDER BY id", $con) or die(mysql_error($con));
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
place the mysql_selectdb() before the mysql_query().

update php database with data of two

I have two tables where I need to display text in a table corresponding to the users of the users table.
So I did this:
$email = $_SESSION['email'];
$select = mysql_query("SELECT t.id, t.id_textos, t.userTitleSite, t.userTextSobre, t.userTextContatos, t.userTextMaisInfos FROM vms_textos t INNER JOIN vms_users u ON (t.id = u.id) LIMIT 1") or print (mysql_error());
while($res_select = mysql_fetch_array($select)){
$userTitleSite = $res_select["userTitleSite"];
$userTextSobre = $res_select["userTextSobre"];
$userTextContatos = $res_select["userTextContatos"];
$userTextMaisInfos = $res_select["userTextMaisInfos"];
$id = $res_select["id"];
and working.
Now i need to update this information straight from the INPUTS..
but I can not do because my field UPDATE must be wrong because it always resets everything after that grip on SUBMIT.
This is the code I'm using. Please see what is wrong:
$query=mysql_query("UPDATE vms_textos SET userTitleSite='$userTitleSite', userTextSobre='$userTextSobre', userTextContatos='$userTextContatos', userTextMaisInfos='$userTextMaisInfos' WHERE t.id=u.id");
Thanks!
[EDIT]
ALL IMPORTANT CODE:
// INCLUDES.PHP
// Starts
ob_start();
session_start();
// Globais
$startaction="";
// Ação
if(isset($_GET["acao"])){
$acao=$_GET["acao"];
$startaction=1;
}
// Conexão com o banco de dados
$conectar=new DB;
$conectar=$conectar->conectar();
// Metodos de Cadastro
if($startaction == 1){
if($acao == "cadastrar"){
$usuario=$_POST["usuario"];
$nome=$_POST["nome"];
$sobrenome=$_POST["sobrenome"];
$telefone=$_POST["telefone"];
$email=$_POST["email"];
$senha=$_POST["senha"];
if(empty($usuario) || empty($nome) || empty($sobrenome) || empty($telefone) || empty($email) || empty($senha)){
$msg="Preencha todos os campos!";
}
// Todos os campos preenchidos
else {
// Email válido
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
// Senha inválida
if(strlen($senha) < 8){
$msg="As senhas devem conter no mínimo oito caracteres!";
}
// Senha válida
else {
// Executa a classe de cadastro
$conectar=new Cadastro;
echo "<div class=\"flash\">";
$conectar=$conectar->cadastrar($usuario, $nome, $sobrenome, $telefone, $email, $senha);
echo "</div>";
}
}
// Email invalido
else{
$msg="Digite seu e-mail corretamente!";
}
}
}
}
// Método de Login
if($startaction == 1){
if($acao == "logar"){
// Dados
$email=addslashes($_POST["email"]);
$senha=addslashes(sha1($_POST["senha"].""));
if(empty($email) || empty($senha)){
$msg="Preencha todos os campos!";
} else{
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$msg="Digite seu e-mail corretamente!";
} else {
// Executa a busca pelo usuário
$login=new Login;
echo "<div class=\"flash\">";
$login=$login->logar($email, $senha);
echo "</div>";
}
}
}
}
// Método de Checar usuário
if(isset($_SESSION["email"]) && isset($_SESSION["senha"])){
$logado=1;
$nivel=$_SESSION["nivel"];
}
// LOGIN.PHP -- CLASSE DE LOGIN
class Login {
public function logar($email, $senha){
$buscar=mysql_query("SELECT * FROM vms_users WHERE email='$email' AND senha='$senha' LIMIT 1");
if(mysql_num_rows($buscar) == 1){
$dados=mysql_fetch_array($buscar);
if($dados["status"] == 1){
$_SESSION["email"]=$dados["email"];
$_SESSION["senha"]=$dados["senha"];
$_SESSION["nivel"]=$dados["nivel"];
setcookie("logado",1);
$log=1;
} else{
$flash="Usuário bloqueado! Entre em contato conosco!";
}
}
if(isset($log)){
$flash="Você foi logado com sucesso!";
} else{
if(empty($flash)){
$flash="Ops, digite seu e-mail e sua senha corretamente!";
}
}
echo $flash;
}
}
// CADASTRO.PHP -- CLASSE DE CADASTRO
class Cadastro{
public function cadastrar($usuario, $nome, $sobrenome, $telefone, $email, $senha){
// Tratamento das variaveis
$usuario=ucwords(strtolower($usuario));
$nome=ucwords(strtolower($nome));
$sobrenome=ucwords(strtolower($sobrenome));
$telefone=ucwords(strtolower($telefone));
$email=ucwords(strtolower($email));
$senha=sha1($senha."");
// Inserção no banco de dados
$validaremail=mysql_query("SELECT * FROM vms_users WHERE email='$email' OR usuario='$usuario'");
$contar=mysql_num_rows($validaremail);
if($contar == 0){
$insert=mysql_query("INSERT INTO vms_users(usuario, nome, sobrenome, telefone, email, senha, nivel, status) VALUES('$usuario','$nome','$sobrenome','$telefone','$email','$senha','1','0')");
} else{
$flash="Desculpe, mas já existe um usuário cadastrado com este e-mail em nosso sistema!";
}
if(isset($insert)){
// Cadatro ok
$flash="Cadastro realizado com sucesso, aguarde nossa aprovação!";
} else{
if(empty($flash)){
$flash="Ops, houve um erro em nosso sistema!";
}
}
// Retorno para o usuário
echo $flash;
}
}
$query=mysql_query("UPDATE vms_textos SET t.userTitleSite='$userTitleSite' WHERE t.id='u.id'");
$query=mysql_query("UPDATE vms_textos SET userTitleSite='$userTitleSite' WHERE t.id=u.id");
what field do u want to update in db? SET that particular field in mysql_query(). i mentioned here.. try like this if u set all fields then all fields are updated..

Categories