przypisanie zmiennej do wyboru w comboboxie

0

Cześć wszystkim.

Mam dwa problemy.

  1. Nie mogę przypisać kodu php do przycisku. Chciałbym żeby wszystko było na jednnej stronie a nie w oddzielnym pliku.
  2. Mam problem z przypisaniem zmiennej do tego co wybiorę w comboboxie.

Chciałbym żeby w comboboxie wybierał nazwy tabel z bazy danych a po naciśnięciu przycisku na tej samej stronie pojawiła się tabela z imionami. Obecnie tabela się pojawia,ale nie potrafię jej przypisać do przycisku oraz mam problem z comboboxie w którym nie potrafię przypisać zmiennej do wyboru.
Proszę o pomoc

Cześć wszystkim.
Chciałbym żeby w comboboxie wybierał nazwy tabel z bazy danych a po naciśnięciu przycisku na tej samej stronie pojawiła się tabela z imionami. Obecnie tabela się pojawia,ale nie potrafię jej przypisać do przycisku oraz mam problem z comboboxie w którym nie potrafię przypisać zmiennej do wyboru.
Proszę o pomoc


<?php


$connection = @mysql_connect('localhost', 'root', '')or die('Brak połączenia z serwerem

MySQL');
mysql_query('SET NAMES utf8');

$db = @mysql_select_db('test', $connection) or die('Nie mogę połączyć się z bazą danych');
$db_name = "test";
mysql_select_db($db_name, $connection);


$wynik = mysql_query("SELECT * FROM test")
$wynik = mysql_query("SELECT * FROM "$name'")->wybór tabeli ma być z comboboxa.
or die('Błąd zapytania');


if(mysql_num_rows($wynik) > 0) {
     echo "<table cellpadding=\"2\" border=1>";
    while($r = mysql_fetch_assoc($wynik)) {
        echo "<tr>";
        echo "<td>".$r['imie']."</td>";
      echo "</tr>";
    }
    echo "</table>";
    echo "</table>";
}
?>

<select name="name">
<option value="test">test</option>
<option value="test1">test1</option>
</select>
<button>Wyslij</button>
0

No to daj opcje w combox:

name = "tabela2"

i to powędruje do zapytania, które wybierze FROM tabela2 i coś tam z tym zrobi

0
  1. Nie używaj znaku @
  2. Nie używaj mysql_ tylko mysqli_ albo najlepiej pdo.
  3. Skoro nie ma nigdzie selecta to trudno abyś coś z niego pobierał, a jeszcze trudniej żeby to coś zmieniało.
0

poprawiłem ale mam dalej problem w linii 20 wyskakuje błąd "
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:20 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(20): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 20".

Jest problem z zapytaniem. Proszę o pomoc.


 <?php

$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';

try{
    
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
} catch (Exception $ex) {

    echo 'Not Connected '.$ex->getMessage();
}

$tableContent = '';
$start = '';
$selectStmt = $con->prepare('SELECT * FROM :start"');
$selectStmt->execute();
$users = $selectStmt->fetchAll();


    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';


if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM :start');

$users = $selectStmt->fetchAll();

    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
    
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title>tabela</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
            
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
        
        <form action="tabela.php" method="POST">
          
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?

>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?

>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?

>>users2</option>

            </select>
            
            <input type="submit" name="search" value="Find">
            
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
                
                <?php
                
                echo $tableContent;
                
                ?>
                
            </table>
            
        </form>
        
    </body>    
</html>

0

Chcesz zbinodować parameter ale tego nie robisz, stąd błąd o ilości parametrów do bindu.
Nie wiem zresztą po co chcesz zbindować start. Nie ma to sensu.

0

a jak 'start' przypisać do pytania sql ?

0

W zapytaniu zrobiłem
$selectStmt = $con->prepare('SELECT * FROM start=$_REQUEST[start]');

ale dalej to nie działa. Pojawia się teraz taki błąd:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[start]' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:22 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(22): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 22

Proszę o pomoc. JAK z selected wydybyć nazwę tabeli żeby ją umieścić w zapytaniu sql.

0

Może spróbuje czegoś takiego

$start = "tabela";
$selectStmt = $con->prepare('SELECT * FROM' . $start);

w ogóle to tamto też powinno działać.

0
przonak007 napisał(a):

W zapytaniu zrobiłem
$selectStmt = $con->prepare('SELECT * FROM start=$_REQUEST[start]');

ale dalej to nie działa. Pojawia się teraz taki błąd:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[start]' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:22 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(22): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 22

Proszę o pomoc. JAK z selected wydybyć nazwę tabeli żeby ją umieścić w zapytaniu sql.

Po co robisz prepare jak wstawiasz na żywca kod do sqla?
weź to zrób po ludzku i zbinduj ten parameter.

0

Ja zrobiłem jak mówił "pol90". Pojawia się taki komunikat:
"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROMtabela' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:22 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(22): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 22"

Gdy zbindowałem parametr, pojawia się komunikat:
"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''start'' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabelabind.php:24 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabelabind.php(24): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabelabind.php on line 24"


<?php
 
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';


try{
 
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
} catch (Exception $ex) {
 
    echo 'Not Connected '.$ex->getMessage();
}
 
$tableContent = '';
$start = "start";
$sql = 'SELECT * FROM tabela = :start';
$selectStmt = $con -> prepare($sql);
$selectStmt -> bindParam(':start', $start);

$selectStmt -> execute();
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM start = ' . $start . '');
 
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
}
 
?>
 $start = $_POST["start"];
<!DOCTYPE html>
<html>
    <head>
        <title>tabela</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
 
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
 
        <form action="tabelabind.php" method="POST">
 
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?>>users2</option>
 
            </select>
 
            <input type="submit" name="search" value="Find">
 
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
 
                <?php
 
                echo $tableContent;
 
                ?>
 
            </table>
 
        </form>
 
    </body>    
</html>
0

Miałem from' zamiast from '.brakowało spacji.
Teraz mam błąd

Czy to jest problem z wyświetleniem danych?
"Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 26

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 27

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 28

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 29

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 40

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 41

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 42

Notice: Undefined variable: user in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 43
$start = $_POST['start']; "

<?php
 
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';


try{
 
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
} catch (Exception $ex) {
 
    echo 'Not Connected '.$ex->getMessage();
}
 
$tableContent = '';
$start = 'users';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);

$selectStmt->execute();
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
if(isset($_POST['search']))
{
$start = $_POST["start"];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
 
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
}
 
?>
 $start = $_POST['start'];
<!DOCTYPE html>
<html>
    <head>
        <title>tabela</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
 
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
 
        <form action="tabela.php" method="POST">
 
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?

>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?

>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?

>>users2</option>
 
            </select>
 
            <input type="submit" name="search" value="Find">
 
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
 
                <?php
 
                echo $tableContent;
 
                ?>
 
            </table>
 
        </form>
 
    </body>    
</html>
0

zmieniłem zmienne z $user na $users, ale to nic nie dało wyświetla się teraz komunikat;

Notice: Undefined index: fname in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 27
Notice: Undefined index: lname in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 28
Notice: Undefined index: age in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 29
Notice: Undefined index: id in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 40
Notice: Undefined index: fname in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 41
Notice: Undefined index: lname in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 42
Notice: Undefined index: age in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 43

0

te indexy to kolumny w tabelach.

0

Może wyciągasz te kolumny do tabel w których nie ma taki kolumn.

0

wszytstko się zgadza: titlehttp://imgur.com/a/RahIg

0

A weź wpisz na sztywno nazwę tabeli i zobacz co się stanie

$selectStmt = $con->prepare('SELECT * FROM tabela);

A drugi przypadek

    $tableContent = $tableContent.'<tr>'.
            '<td>'.$users[0].'</td>'
            .'<td>'.$users[1].'</td>'
            .'<td>'.$users[2].'</td>'
            .'<td>'.$users[3].'</td>';

I sprawdź te dwa przypadki i zobacz co się stanie.

0

Dodałem foreach ($users as $users) przed $tableContent = $tableContent.''. i wstawiłem pełną nazwę tabeli i działa,ale ja wstawiłem twój sposób to wystąpił błąd:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:20 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(20): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 20

 <?php

$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';

try{
    
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
} catch (Exception $ex) {

    echo 'Not Connected '.$ex->getMessage();
}

$tableContent = '';
$start = '';
$selectStmt = $con->prepare('SELECT * FROM users');
$selectStmt->execute();
$users = $selectStmt->fetchAll();

foreach ($users as $users)
{
  $tableContent = $tableContent.'<tr>'.
            '<td>'.$users['id'].'</td>'
            .'<td>'.$users['fname'].'</td>'
            .'<td>'.$users['lname'].'</td>'
            .'<td>'.$users['age'].'</td>';
}

if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM users');
$selectStmt->execute();

$users = $selectStmt->fetchAll();

foreach ($users as $users)
{
  $tableContent = $tableContent.'<tr>'.
            '<td>'.$users['id'].'</td>'
            .'<td>'.$users['fname'].'</td>'
            .'<td>'.$users['lname'].'</td>'
            .'<td>'.$users['age'].'</td>';
}
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title>Tabela</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
            
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
        
        <form action="tabela.php" method="POST">
            
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?>>users2</option>
            </select>
            
            <input type="submit" name="search" value="Find">
            
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
                
                <?php
                
                echo $tableContent;
                
                ?>
                
            </table>
            
        </form>
        
    </body>    
</html>
0

jak podstawiam zmienną $start to występuje błąd.

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\dashboard\test\combobox\tabela.php:20 Stack trace: #0 C:\xampp\htdocs\dashboard\test\combobox\tabela.php(20): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dashboard\test\combobox\tabela.php on line 20"

$selectStmt = $con->prepare('SELECT * FROM ' .$start);

0

<?php

$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';

try{
    
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
} catch (Exception $ex) {

    echo 'Not Connected '.$ex->getMessage();
}

$tableContent = '';
$start = '';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();
$users = $selectStmt->fetchAll();

foreach ($users as $user)
{
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
}

if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();

$users = $selectStmt->fetchAll();


    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
    
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title>Search & Display Using Selected Values</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
            
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
        
        <form action="table_selected_valueeee.php" method="POST">
            
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?>>users2</option>
            </select>
            
            <input type="submit" name="search" value="Find">
            
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
                
                <?php
                
                echo $tableContent;
                
                ?>
                
            </table>
            
        </form>
        
    </body>    
</html>
0

nic się nie zmieniło tylko wystąpił nowy problem:
Notice: Undefined index: start in C:\xampp\htdocs\dashboard\test\combobox\table_selected_valueeee.php on line 18


<?php
 
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';
 
try{
 
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
} catch (Exception $ex) {
 
    echo 'Not Connected '.$ex->getMessage();
}
 
$tableContent = '';
$start = $_POST['start'];
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();
$users = $selectStmt->fetchAll();
 
foreach ($users as $user)
{
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
}
 
if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();
 
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
}
 
?>
 
<!DOCTYPE html>
<html>
    <head>
        <title>Search & Display Using Selected Values</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
 
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
 
        <form action="table_selected_valueeee.php" method="POST">
 
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?>>users2</option>
            </select>
 
            <input type="submit" name="search" value="Find">
 
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
 
                <?php
 
                echo $tableContent;
 
                ?>
 
            </table>
 
        </form>
 
    </body>    
</html>
0

Zobacz czy ten kod działa ?

 
<?php
 
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '';
 
try{
 
    $con = new PDO($dsn, $username, $password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
} catch (Exception $ex) {
 
    echo 'Not Connected '.$ex->getMessage();
}
 
$tableContent = '';
if(isset($_POST['search'])) {
$start = $_POST['start'];
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();
$users = $selectStmt->fetchAll();
 
foreach ($users as $user)
{
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
}
 }
if(isset($_POST['search']))
{
$start = $_POST['start'];
$tableContent = '';
$selectStmt = $con->prepare('SELECT * FROM ' .$start);
$selectStmt->execute();
 
$users = $selectStmt->fetchAll();
 
    $tableContent = $tableContent.'<tr>'.
            '<td>'.$user['id'].'</td>'
            .'<td>'.$user['fname'].'</td>'
            .'<td>'.$user['lname'].'</td>'
            .'<td>'.$user['age'].'</td>';
 
}
 
?>
 
<!DOCTYPE html>
<html>
    <head>
        <title>Search & Display Using Selected Values</title>  
        <style>
            table,tr,td
            {
               border: 1px solid #000; 
            }
 
            td{
                background-color: #ddd;
            }
        </style>   
    </head>
    <body>
 
        <form action="table_selected_valueeee.php" method="POST">
 
            <select name="start">
                <option value="">...</option>
                <option value="users" <?php if($start == 'users'){echo 'selected';}?>>users</option>
                <option value="users1" <?php if($start == 'users1'){echo 'selected';}?>>users1</option>
                <option value="users2" <?php if($start == 'users2'){echo 'selected';}?>>users2</option>
            </select>
 
            <input type="submit" name="search" value="Find">
 
            <table>
                <tr>
                    <td>#ID</td>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Age</td>
                </tr>
 
                <?php
 
                echo $tableContent;
 
                ?>
 
            </table>
 
        </form>
 
    </body>    
</html>
0

Co Wy kombinujecie?

<?php

$users = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $dsn      = 'mysql:host=localhost;dbname=test';
    $username = 'root';
    $password = 'root';

    try
    {
        $conn = new PDO($dsn, $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->exec("set names utf8");
    }
    catch (Exception $ex)
    {
        echo 'Not Connected ' . $ex->getMessage();
        exit(1);
    }

    $tableName = $_POST['tableName'];

    if (!empty($tableName))
    {
        $stmt = $conn->prepare('SELECT * FROM ' . $tableName);
        $stmt->execute();
        $users = $stmt->fetchAll();
    }
    else
    {
       echo 'No table selected.';
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Search & Display Using Selected Values</title>
        <meta charset="utf8" />
        <style>
            table,tr,td {border: 1px solid #000; }
            td { background-color: #ddd; }
        </style>
    </head>
    <body>
        <form action="index.php" method="POST">
            <select name="tableName">
                <option value="" style="display:none" <?php if (!isset($tableName)) echo 'selected="selected"' ?>>...</option>
                <option value="users" <?php if (isset($tableName) && ($tableName === 'users')) echo 'selected="selected"' ?>>users</option>
                <option value="users1" <?php if (isset($tableName) && ($tableName === 'users1')) echo 'selected="selected"' ?>>users1</option>
                <option value="users2" <?php if (isset($tableName) && ($tableName === 'users2')) echo 'selected="selected"' ?>>users2</option>
            </select>
            <input type="submit" name="search" value="Find">
        </form>
        <table>
            <tr>
                <td>#ID</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Age</td>
            </tr>
            <!-- To chyba bardziej praktyczne dawanie tych znacznikow w petli w kodzie PHP wyzej :-) -->
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $user['id'] ?></td>
                <td><?= $user['fname'] ?></td>
                <td><?= $user['lname'] ?></td>
                <td><?= $user['age'] ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </body>
</html>

Dobrze to najpierw sprawdziłem, przed wklejeniem tutaj. Nawet polskie pod względem polskich nazw i tego, że żadna z tabel może nie zostać wybrana...

0

Wszystko działa, ale mam pytanie. Chciałbym dodać jeszcze jeden combobox z numerem id oraz dwa datepicker (które wyświetlą przedział daty urodzenia) .
Zapytanie miało by wyglądać tak:
SELECT * FROM users WHERE id = 1 AND age BETWEEN '2017-07-04' and '2017-07-05'

'SELECT * FROM ‘.$tableName WHERE id = ‘.$tableName 1 AND age BETWEEN Data1 and Data2

Stworzyłem następny combobox oraz dwa datepicker, ale nie mogę sobie poradzić żeby przypisać do zapytania SQL. Proszę o pomoc.

Poniżej jest kod z moimi poprawami.

<?php
 
$users = array();
 
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $dsn      = 'mysql:host=localhost;dbname=test';
    $username = 'root';
    $password = '';
 
    try
    {
        $conn = new PDO($dsn, $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->exec("set names utf8");
    }
    catch (Exception $ex)
    {
        echo 'Not Connected ' . $ex->getMessage();
        exit(1);
    }
 
    $tableName = $_POST['tableName'];
 
    if (!empty($tableName))
    {
        $stmt = $conn->prepare('SELECT * FROM ' . $tableName);
        $stmt->execute();
        $users = $stmt->fetchAll();
    }
    else
    {
       echo 'No table selected.';
    }


}
?>
 
<!DOCTYPE html>
<html>
    <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <title>Search & Display Using Selected Values</title>
        <meta charset="utf8" />
        <style>
            table,tr,td {border: 1px solid #000; }
            td { background-color: #ddd; }
        </style>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
  } );
  </script>
 <script>
  $( function() {
    $( "#datepicker2" ).datepicker({ dateFormat: 'yy-mm-dd' });
  } );
  </script>
    </head>
    <body>
        <form action="" method="POST">
            <select name="tableName">
                <option value="" style="display:none" <?php if (!isset($tableName)) echo 'selected="selected"' ?>>...</option>
                <option value="users" <?php if (isset($tableName) && ($tableName === 'users')) echo 'selected="selected"' ?>>users</option>
                <option value="users1" <?php if (isset($tableName) && ($tableName === 'users1')) echo 'selected="selected"' ?>>users1</option>
                <option value="users2" <?php if (isset($tableName) && ($tableName === 'users2')) echo 'selected="selected"' ?>>users2</option>
            </select>

<select name="tableName1">
                <option value="" style="display:none" <?php if (!isset($tableName1)) echo 'selected="selected"' ?>>...</option>
                <option value="1" <?php if (isset($tableName1) && ($tableName1 === '1')) echo 'selected="selected"' ?>>1</option>
                <option value="2" <?php if (isset($tableName1) && ($tableName1 === '2')) echo 'selected="selected"' ?>>2</option>
            </select>
            <input type="submit" name="search" value="Find">
        </form>



<p>Date: <input type="text" name="Data1" id="datepicker" style="width: 58px; font-size:10px" /></p>
<p>Date: <input type="text" name="Data2" id="datepicker2" style="width: 58px; font-size:10px" /></p>

        <table>
            <tr>
                <td>#ID</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Age</td>
            </tr>

            <!-- To chyba bardziej praktyczne dawanie tych znacznikow w petli w kodzie PHP wyzej :-) -->
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $user['id'] ?></td>
                <td><?= $user['fname'] ?></td>
                <td><?= $user['lname'] ?></td>
                <td><?= $user['age'] ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </body>
</html>



1

Tylko że ja tu kompletnie nie rozumiem co chcesz osiągnąć umieszczając dane w kilku tabelach zamiast w jednej? No i po co to pole wyboru ID? Ale jeśli są tabele users, users1, users2 to każda z nich ma mieć taki schemat:

CREATE TABLE  `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `fname` varchar(45) NOT NULL,
  `lname` varchar(45) NOT NULL,
  `birthdate` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

A tutaj kod. Z bootstrap wygląda to lepiej :-)

$users = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $dsn      = 'mysql:host=localhost;dbname=test';
    $username = 'root';
    $password = 'root';

    try
    {
        $conn = new PDO($dsn, $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->exec("set names utf8");
    }
    catch (Exception $ex)
    {
        echo 'Not Connected ' . $ex->getMessage();
        exit(1);
    }

    $tableName = $_POST['tableName'];
    $date1 = $_POST['date1'];
    $date2 = $_POST['date2'];

    if (!empty($tableName))
    {
        $stmt = $conn->prepare('SELECT * FROM '.$tableName.' WHERE birthdate BETWEEN :date1 AND :date2');
        $stmt->execute(array(':date1' => $date1, ':date2' => $date2));
        $users = $stmt->fetchAll();
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Search & Display Using Selected Values</title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    </head>
    <body>
    <div class="container">
        <div class="jumbotron">
            <h1>Search and Display</h1>
            <p>Search using selected tables and datepickers</p>
        </div>
        <form action="" method="POST" class="form form-inline">
        <div class="form-group">
            <label class="control-label" for="tableName">Table:</label>
            <select name="tableName" id="tableName" class="form-control" required>
                <option value="" style="display:none" <?php if (!isset($tableName)) echo 'selected="selected"' ?>>...</option>
                <option value="users" <?php if (isset($tableName) && ($tableName === 'users')) echo 'selected="selected"' ?>>users</option>
                <option value="users1" <?php if (isset($tableName) && ($tableName === 'users1')) echo 'selected="selected"' ?>>users1</option>
                <option value="users2" <?php if (isset($tableName) && ($tableName === 'users2')) echo 'selected="selected"' ?>>users2</option>
            </select>
        </div>
        <div class="form-group">
            <label class="control-label" for="datepicker1">From date:</label>
            <input type="text" name="date1" id="datepicker1" class="form-control" value="<?= isset($date1) ? $date1 : '' ?>" required/>
        </div>
        <div class="form-group">
            <label class="control-label" for="datepicker2">From date:</label>
            <input type="text" name="date2" id="datepicker2" class="form-control" value="<?= isset($date2) ? $date2 : '' ?>" required/>
        </div>
        <input type="submit" name="search" class="btn btn-default" value="Find">
        </form>

        <table class="table table-condensed">
            <thead>
                <th>#ID</td>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Birth Date</th>
            </thead>
            <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $user['id'] ?></td>
                <td><?= $user['fname'] ?></td>
                <td><?= $user['lname'] ?></td>
                <td><?= $user['birthdate'] ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
      </div>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
      $( function() {
          $( "#datepicker1" ).datepicker({ dateFormat: 'yy-mm-dd' });
          $( "#datepicker2" ).datepicker({ dateFormat: 'yy-mm-dd' });
      } );
      </script>
    </body>
</html>

Czyli zamiast age to w tabelach pole bitrhdate jako DATETIME czyli data urodzenia i po tym będzie sprawdzane. W zasadzie można by też użyć INT(10) do zapisywania daty urodzenia jako Unix Timestamp no ale to działa od 1970 r, więc w zasadzie nie nadaje się w tym zastosowaniu, bo wiadomo że użytkownicy mogli urodzić się wcześniej.

0

chciałbym jeszcze zastosować combobox do selekcji nazwiska. Nie wiem jak to wstawić ten kod,


<select name="tableName1" id="tableName" class="form-control" required>
<option value="" style="display:none" <?php if (!isset($tableName)) echo 'selected="selected"' ?>>...</option>
                <option value="nowak" <?php if (isset($tableName) && ($tableName === 'nowak')) echo 'selected="selected"' ?>>users</option>
                <option value="kowalski" <?php if (isset($tableName) && ($tableName === 'kowalski')) echo 'selected="selected"' ?>>users1</option>
                <option value="kowalczyk" <?php if (isset($tableName) && ($tableName === 'kowalczyk')) echo 'selected="selected"' ?>>users2</option>
            </select>
1

A Ty zwracasz w ogóle uwagę na konieczność zastosowania odpowiednich nazw? Raz że polecenie SQL ulegnie zmianie, dwa że w tym kodzie są grupy label - input opakowane to wszystko w div class form-group.

<?php

$users = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $dsn      = 'mysql:host=localhost;dbname=test';
    $username = 'root';
    $password = '';

    try
    {
        $conn = new PDO($dsn, $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->exec("set names utf8");
    }
    catch (Exception $ex)
    {
        echo 'Not Connected ' . $ex->getMessage();
        exit(1);
    }

    $tableName = $_POST['tableName'];
    $lastName = $_POST['lastName'];
    $date1 = $_POST['date1'];
    $date2 = $_POST['date2'];

    if (!empty($tableName))
    {
        $stmt = $conn->prepare('SELECT * FROM '.$tableName.' WHERE (lname = :lname) AND (birthdate BETWEEN :date1 AND :date2)');
        $stmt->execute(array(':lname' => $lastName, ':date1' => $date1, ':date2' => $date2));
        $users = $stmt->fetchAll();
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Search & Display Using Selected Values</title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    </head>
    <body>
    <div class="container">
        <div class="jumbotron">
            <h1>Search and Display</h1>
            <p>Search using selected tables and datepickers</p>
        </div>
        <form action="" method="POST" class="form form-inline">
        <div class="form-group">
            <label class="control-label" for="tableName">Table:</label>
            <select name="tableName" id="tableName" class="form-control" required>
                <option value="" style="display:none" <?php if (!isset($tableName)) echo 'selected="selected"' ?>>...</option>
                <option value="users" <?php if (isset($tableName) && ($tableName === 'users')) echo 'selected="selected"' ?>>users</option>
                <option value="users1" <?php if (isset($tableName) && ($tableName === 'users1')) echo 'selected="selected"' ?>>users1</option>
                <option value="users2" <?php if (isset($tableName) && ($tableName === 'users2')) echo 'selected="selected"' ?>>users2</option>
            </select>
        </div>
        <div class="form-group">
            <label class="control-label" for="lastName">Last name:</label>
            <select name="lastName" id="lastName" class="form-control" required>
                <option value="" style="display:none" <?php if (!isset($lastName)) echo 'selected="selected"' ?>>...</option>
                <option value="Nowak" <?php if (isset($lastName) && ($lastName === 'Nowak')) echo 'selected="selected"' ?>>Nowak</option>
                <option value="Kowalski" <?php if (isset($lastName) && ($lastName === 'Kowalski')) echo 'selected="selected"' ?>>Kowalski</option>
                <option value="Kowalczyk" <?php if (isset($lastName) && ($lastName === 'Kowalczyk')) echo 'selected="selected"' ?>>Kowalczyk</option>
            </select>
        </div>
        <div class="form-group">
            <label class="control-label" for="datepicker1">From date:</label>
            <input type="text" name="date1" id="datepicker1" class="form-control" value="<?= isset($date1) ? $date1 : '' ?>" required/>
        </div>
        <div class="form-group">
            <label class="control-label" for="datepicker2">From date:</label>
            <input type="text" name="date2" id="datepicker2" class="form-control" value="<?= isset($date2) ? $date2 : '' ?>" required/>
        </div>
        <input type="submit" name="search" class="btn btn-default" value="Find">
        </form>

        <table class="table table-condensed">
            <thead>
                <th>#ID</td>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Birth Date</th>
            </thead>
            <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $user['id'] ?></td>
                <td><?= $user['fname'] ?></td>
                <td><?= $user['lname'] ?></td>
                <td><?= $user['birthdate'] ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
      </div>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
      $( function() {
          $( "#datepicker1" ).datepicker({ dateFormat: 'yy-mm-dd' });
          $( "#datepicker2" ).datepicker({ dateFormat: 'yy-mm-dd' });
      } );
      </script>
    </body>
</html>

Zobacz co się zmieniło w tym kodzie w porównaniu do poprzedniej wersji z poprzedniego postu. Widać dość jasno gdzie należy wstawiać kolejne cześci kodu.

0

drorat1 jesteś wielki, pomysł na sql jest fantastyczny, Bardzo dziękuję wszystkim za pomoc.

1 użytkowników online, w tym zalogowanych: 0, gości: 1