Add column in MySQL with number of total columns as title - php

How can I add a new column in the table named "tische" with the column-title of the total columns in this table?
I tried following codem but that doesn't work...
<?php
//Creating an sql query
$number = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tische'";
$rs = mysqli_query($number);
$result = mysqli_fetch_array($rs);
$add = "ALTER TABLE tische ADD COLUMN `$result` VARCHAR(100) NOT NULL AFTER zeit";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if (mysqli_query($con, $add)) {
echo 'Element erfolgreich hinzugefügt';
} else {
echo 'Fehler!';
}
//Closing the database
mysqli_close($con);
When I execute the querys in the console of phpMyadmin, it works. But not in this php-script... Please help me

Add require_once('dbConnect.php'); in page of top. Add $con variable in mysqli_query first param like $rs = mysqli_query($con, $number);
SYNTAX of mysqli_query :
mysqli_query(mysqli $con , string $query [, int $resultmode = MYSQLI_STORE_RESULT ])
Your correction code is bellow :
<?php
//Importing our db connection script
require_once('dbConnect.php');
//Creating an sql query
$number = "SELECT COUNT(*) as total FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tische'";
$rs = mysqli_query($con, $number);
$column_name = 0;
if(mysqli_num_rows($rs) > 0) {
while($result = mysqli_fetch_array($rs)) {
$column_name = $result['total'];
}
$add = "ALTER TABLE tische ADD COLUMN `$column_name` VARCHAR(100) NOT NULL AFTER zeit";
//Executing query to database
if(mysqli_query($con,$add)){
echo 'Element erfolgreich hinzugefügt';
} else {
echo 'Fehler!';
}
}
//Closing the database
mysqli_close($con);
?>

Related

How to update data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one Update in table "TabelaX" which is in another database. I already made some code but it is not working correctly.
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
mysqli_select_db($conn,"Servidor1");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Data"];
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Servidor1.TabelaX (ID, Data)
SELECT ID, Data
FROM Servidor3.TabelaW
WHERE ID = $ID;";
$sql = "UPDATE Servidor1.TabelaX SELECT ID, Data FROM
Servidor3.TabelaW SET Data = $row2 WHERE $row1 = $ID;";
if (mysqli_multi_query($conn, $sql)) {
echo "Dados Inseridos";
} if (mysqli_multi_query($conn, $sql)) {
echo "Dados Atualizados";
}
mysqli_close($conn);
I have no idea what your query is trying to do, because you assign to $sql twice without ever executing the first query, but if you're asking how to update a row in tableX based on data from tableY, then:
UPDATE Servidor1.TabelaX as x, Servidor2.TabelaY as y
SET x.Data = y.Data
WHERE x.id = y.id
AND x.id = $someIdForWhichYouWantToUpdate
Also, do not do this:
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
Imagine what happens when the user posts 1; DROP DATABASE Servidor1 into the form. This is called SQL injection and your code is full of vulnerabilities to it.

Getting the AUTO_INCREMENT value from php(not working)

I have a simple mysqli code to select the current AUTO_INCREMENT value in a table named bookings.
After the code executes, nothing happens.I do not get any output in the screen.
Here is the code.
if ($result = mysqli_query($conn, "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = titan3d AND TABLE_NAME = bookings", MYSQLI_USE_RESULT)) {
if (!mysqli_query($conn, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($conn));
}
myslqi_stmt_fetch_assoc($result);
var_dump($result);
}
Is there something wrong with this code.Can somebody sort it out?
You have a syntax error in the query, you didn't quote the strings. And then you need to fetch the result row.
if ($result = mysqli_query($conn, "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'titan3d' AND TABLE_NAME = 'bookings'", MYSQLI_USE_RESULT)) {
$row = mysqli_fetch_assoc($result);
echo "Auto-increment is {$row['AUTO_INCREMENT']}";
} else {
echo mysqli_error($conn);
}

SQL query doesn't get values

The SQL query returns just Array in the browser even if there is values in the database. I have tried the query in phpmyadmin and it works but not in my php document.
require_once('connect.php');
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
Almost the same query works in different php documents. Any suggestions what is wrong? Should also say that the query should return integers.
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
You're only selecting the id column. If you wish to echo more columns, then you need to add them in the query.
I.e.:
$query = "SELECT `id`, `col2`, `col3` FROM `questions` WHERE round=1 AND year=2016";
then loop over results:
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
echo $row['id'];
// echo "<br>";
// echo $row['col2'] . "<br>";
// echo $row['col3'];
}
Check for errors on the query also and assuming a successful mysqli_ connection.
http://php.net/manual/en/mysqli.error.php
Other reference:
http://php.net/manual/en/function.mysqli-connect.php
if you want to display other column's data so have to add * in the place of 'id'
require_once('connect.php');
$query = "SELECT * FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);

Clear SQL table before importing data (php)

Hi guys as the title says i'm trying to clear My SQL table before importing new data , but the problem only the last two rows appears not all of them .
I tried this using "TRUNCATE"
// clear table
$sqli = "TRUNCATE TABLE MyTable";
mysql_query($sqli);
$sql = 'INSERT INTO MyTable VALUES("'.$Data1.'","'.$Data2.'") ';
mysql_query($sql);
mysql_close();
$sql = 'SELECT * FROM MyTable';
$req = mysql_query($sql);
while($data = mysql_fetch_array($req)){
$D1 = $data['data1'];
$D2 = $data['data2'];
echo "$D1<br />
$D2<br />";
}
i can see only the last two rows.
this is full code
part 1 : adding data into MySQL table
<?php
include( "............" );
$table = mta::getInput();
$Kills = $table[0];
$Deaths = $table[1];
// Send infos in MySQL
$base = mysql_connect ('........', '.........', '........');
mysql_select_db ('.........', $base);
$sql = 'INSERT INTO AccountsData VALUES("'.$Kills.'","'.$Deaths.'") ';
mysql_query($sql);
mysql_close();
// Return true if is added
// an other code here
?>
part 2 : get data from Mysql Table
<?php
$base = mysql_connect ('.........', '.........', '.........');
mysql_select_db ('..........', $base);
$sql = 'SELECT * FROM AccountsData';
$req = mysql_query($sql);
while($data = mysql_fetch_array($req)){
$Kills = $data['Kills'];
$Deaths = $data['Deaths'];
echo "$Kills<br />
$Deaths<br />";
}
mysql_close();
?>
before using "TRUNCATE TABLE" it's working fine and i can see all rows
like this:
example
player 1
player 2
player 3
player 4
after using "TRUNCATE TABLE" i can see only the last row
player 4.
All what i need is i want to clear the table before adding new rows.
Sorry it's the first time that i use https://stackoverflow.com/

mySql query does not find the row

I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");

Categories