I have an array of column names and column data types and now i wish to create a mysql table using these two arrays. Here's my code so far:
<?php
//print_r($_GET);
$col_names=[]; //this will store column names received from user
$col_types=[];//this will store column data types selected by user
if(isset($_GET['col_num'])){
$table_name=$_GET['table_name'];
$n=$_GET['col_num'];
for($i=0;$i<$n;$i=$i+1){
$index_names = "col".$i;
$index_type = "type".$i;
$col_names[$i] = $_GET[$index_names];
$col_types[$i] = $_GET[$index_type];
}
}
$con=mysqli_connect('localhost','root');
if(!$con){
die("Error conncecting: ". mysqli_error($con));
}
else{
mysqli_select_db($con,'temp');
$query = "CREATE TABLE $table_name (
for($i=0; $i<$n ;$i=$i+1)
{
echo "$col_names[$i]" . " " . "$col_types[$i]" . "(10)"
}
);";
/*
If suppose the col_names array contains : [Name,Age] and col_types contains: [Varchar,Int] then i need these two attributes to be incorporated in my Create query and so i have put them in a for loop.
*/
mysqli_query($query);
}
?>
Now i know that something's wrong with the "Create Query" that i have written but i am not able to figure out how to frame the query.Also how should i place the comma in case of multiple columns?
You are doing wrong, Use something like this,
$query = "CREATE TABLE $table_name ( ";
for($i=0; $i<$n ;$i=$i+1)
{
$query .= "$col_names[$i]" . " " . "$col_types[$i]" . "(10)" ;
}
$query .= " ); ";
echo $query;//output and check your query
mysqli_query($query);
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have 2 php files. One of them creates a table and inserts data into MySql using php. The other php selects the table in the database and outputs the data from the table. The table is outputting 0 results as in there aren't any record being stored into the table.
Need help, Thanks!
//select from table
$sql = "SELECT * FROM post02";
$result = mysql_query($link, $sql);
echo 'selecting table works';
//output from table
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["title"]. " " . $row["content"]. "" . $row["date"]."<br>";
}
} else {
echo "0 results";
}
// create a table
$sql="create table post02(id INT(6) unsigned auto_increment primary key , title varchar(30) not null, content varchar(255) not null, date TIMESTAMP)";
$result = mysql_query($sql);
if (! $result ) {
die ( 'Cant create table : ' . mysql_error ());
}
echo 'Created a table successfuly' ;
//insert to table
echo'insert table - initializing';
if($_POST['submit']){
$title = $_POST['title'];
$content = $_POST['content'];
$date = date('l jS \of F Y h:i:s A');
}
$sql = "INSERT INTO post02(title, content, date) VALUES ($title, $content,$date))";
if($title =="" || $content=="" ){
echo "please compelete your post!";
return;
}
echo'insert table completed';
mysql_query($db ,$sql);
header("location: viewblog.php");
Why are these on your code "mysql_query($db ,$sql);" and " mysql_query($link, $sql);" mysql_query takes just one parameter
mysql_query accepts query as first parameter & connection string as second parameter. Try interchanging in all the locations in your code. Or you can remove the link parameter
I would like to start from an example: you received some list with needed fields. This list may vary and even if it is empty, select all fields. This list can include fields from several tables. Is there any way to generate SELECT query for doing this?
Probably there is a way, but it will look like parsing received list, adding appropriate table alias, and then adding modified list into select clause. Is it best way actually?
Update 1
The goal is only to get passed fields from several tables, not to
control result from any of them(its about first answer)
You could create a query that first selects dynamically fields, depending on your criteria.
for example lets assume you have two criteria passed to you. Then (after you have made sure your criteria1 and criteria2 are safe):
$mySelect = ''; //placeholder so that you can add select fields
$extraTables = ''; //placeholder to put the extra tables I may need
$criteria = " WHERE 1 "; //this will select everything
if ($criteria1>'') {
$mySelect .= ' , t3.field3 ';
$extraTables = " , aDifferentTable AS t3";
$criteria .= " AND t3.someKey = t1.someKey '";
$criteria .= " AND field_crit1 = '" . $criteria1 . "'";
}
//and an example of connecting dynamically to an other table
if ($criteria2>'') {
$mySelect .= ' , t2.field5 ';
$extraTables = " , anOtherTable AS t2";
$criteria .= " AND t2.someKey = t1.someKey '";
$criteria .= " AND t2.field_crit2 = '" . $criteria2 . "'";
}
//lets combine all together into one dynamically created query
$myquery = "SELECT t1.something " . $mySelect . " FROM myTable AS t1";
$myquery = $myqury . $extraTables . $criteria;
I am looking to post data into two database tables from a single form.
My databases are arranged as below:
Database 1 - 'watchlists':
watchlist_id
user_id
name
description
category
Database 2 - 'watchlist_films':
watchlist_id
film_id
My current MySQL query looks like this: $query = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$watchlist_name['watchlist_id']', '$rt_id') WHERE watchlists ('watchlist_id') = " . $watchlist_name['watchlist_id'];, but I'm not sure if there's got to be some form of INNER JOIN somewhere?
Not sure what other information/code to provide, so I apologise if there's too little detail here, but, if there's anything else which is needed, just drop me a comment and I'll put up anything else which is required. I'm a relative PHP newbie, so apologies if this seems like a really simple question!
Update based on comments:
I have now got half of my query working, and have updated the logic to reflect it. The new query is basically doing the following:
INSERT new Watchlist to 'watchlists' table
SELECT watchlist_id of new Watchlist from 'watchlists' table WHERE watchlist_name = $watchlist_name (name of new Watchlist just created) and user_id = $user_id
INSERT watchlist_id (selected from previous query) AND film_id into 'watchlist_films' table
based on your comments, my queries now look like so:
if ($submit == 'Submit') {
require_once("db_connect.php");
$watchlist_name = clean_string($_POST['watchlist-name']);
$watchlist_description = clean_string($_POST['watchlist-description']);
$watchlist_category = $_POST['watchlist-category'];
$addWatchlist_bad_message = '';
$addWatchlist_good_message = '';
if ($db_server) {
if (!empty($watchlist_name)) {
$watchlist_name = clean_string($watchlist_name);
$watchlist_description = clean_string($watchlist_description);
mysql_select_db($db_database);
// Insert new Watchlist into Watchlist index
$insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);
// Select new Watchlist ID
$select_new_watchlist = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
$new_watchlist_id = mysql_query($select_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $select_new_watchlist);
// Add film to new Watchlist
$add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
$addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully!</div>';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
} else {
$addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
require_once("db_close.php");
}
My query, however, seems to be failing at the SELECT statement, in between adding the new Watchlist to the Watchlist index and adding the film to the newly created Watchlist.
try this
$query1 = "INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')";
$query2= "INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")";
$result = mysqli_multi_query($query1, $query2);
You will need to write an INSERT for each table.
$mysqli->query("INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')");
$mysqli->query("INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")");
That's the function which I'm using to print the contents of 'username' table:
function showtable()
{
ob_start();
$db = new PDO("sqlite:test.db");
$query = "SELECT * FROM " . $_SESSION['username'] . " ORDER BY `a` DESC;";
$result = $db->prepare($query);
$result = $db->query($query);
print "<table>";
print "<tr><td>First Column</td><td>Second Column</td><td>Third column</td></tr>";
foreach ($result as $row)
{
print "<tr><td>" . $row['a'] . "</td><td>" . $row['b'] . "</td><td>Here stays the button</td></tr>";
}
print "</table>";
unset($db);
ob_end_flush();
}
So, how should look a function so when creating each row of the html table, a button for updating the corresponding sqlite table row is inserted in the third cell (named 'Here stays the button' for easier reading)? I'm calling my function when opening the test.php (with added required_once('functions.php')) file in main browser window, nothing special in that.
That's the UPDATE query:
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = " . $row['a'] . ";";
a column is integer primary key
b column is text
c column is integer, all fields hold 0 value
P.S. Don't talk about AJAX, I'm not ready for it (and don't like it, a lot of pages that use AJAX lag the browser). Just asking for ideas about a simple php function, that adds UPDATE TABLE functionality through buttons for each row.
Thanks in advance :)
What is the updating for? what will happen if C = 1?
anyway for your question, my suggestion is to use an anchor tag.
i.e
in the "Here stays the button" will be Update
in your test.php
if($_GET['a_new'] != '')
{
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = ".$_GET['a_new']."";
}
p.s you have excess ";" in your query. you only add the query on the end of the query statement not inside it i.e $sql = "select * from"; not $sql = "select * from;";
This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL.
I've bolded the most pertinent section of code.
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
As for your id question...that's how ids work. They don't fill in gaps.
On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().
SELECT * FROM test ORDER BY Id DESC LIMIT 1