Getting the AUTO_INCREMENT value from php(not working) - php

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);
}

Related

PHP : Continue get me out

Why my second if is never executed ? It seems like the continue sentence get me out of the foreach. I have tried the elseif without success.
foreach($columns as $i=>$column)
{
// Check if column exists
$sql = "SELECT '$column' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database' AND TABLE_NAME = '$strTable'";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
continue;
}
$sql = "alter table '$strTable' add column '$column' varchar (30)";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
}
$cols .= $column.',';
}
You're not testing whether the query found any rows. mysqli_real_query() is successful as long as it didn't get an error, but that doesn't mean the query matched anything. You need to get the result of the query.
Also, you're just checking whether the table exists, not whether that column exists in the table.
continue skips the entire rest of the loop body. You should use else to execute the second block when the column isn't found.
Use mysqli_query() if you want to use the result. Otherwise, you need to call mysqli_use_result() and mysqli_store_result() first; see difference between mysqli_query and mysqli_real_query
foreach($columns as $column)
{
// Check if column exists
$sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$database' AND TABLE_NAME = '$strTable' AND COLUMN_NAME = '$column'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0)
{
echo 'Column '.$column.' already exists! <br>';
} else {
$sql = "alter table '$strTable' add column '$column' varchar (30)";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
}
}
$cols .= $column.',';
}

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.

Add column in MySQL with number of total columns as title

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);
?>

List all tables within DB

I am trying to show a list of all tables within my database
I have the below code:
$result=mysql_query("SELECT TABLE_NAME FROM vogaldes_fuse.INFORMATION_SCHEMA.Tables ")or die('ERROR 315' );
$num_rows = mysql_num_rows($result);
echo "$num_rows";
However this does not show any results, instead i see ERROR 315
Also, I want to list the table names, how do I get these?
UPDATE
I have managed to get the correct number of tables using the below:
$result=mysql_query("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse';")or die('ERROR 315' );
The last bit of my question still stand, how do I turn each table name into a string that I can then use to list in a select dropdown?
Just use select TABLE_NAME from information_schema.tables Remove vogaldes_fuse. database name
To create dropdown of table use
$result = mysql_query("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse'") or die('ERROR 315');
if (mysql_num_rows($result) > 0) {
echo "<select name='table_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['TABLE_NAME'] . "'>" . $row['TABLE_NAME'] . "</option>";
}
echo "</select>";
}
UPDATED
For select TABLE_SCHEMA except some table
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'vogaldes_fuse' AND TABLE_NAME NOT
IN (
'hr_employees', 'hr_roles'
)
Run This
USE 'your db name';
SHOW TABLES;
SELECT FOUND_ROWS();
Use This
$sql = "SHOW TABLES FROM 'your db name'";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}</br>";
}
mysql_free_result($result);
Hope this help .
For MySQL:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='dbName'

Error: Unknown column 'joinedactivities.searchact id = searchact.id' in 'on clause'

I keep getting this error Error: Unknown column 'joinedactivities.searchact id = searchact.id' in 'on clause'. I have checked table names and tried changing it but I keep getting errors.
I have tables:
joinedactivities- id, user id(foreign key), searchact id(foreign key)
searchact-id,postcode, lat, long, hobby, venue
I am trying to display rows from table searchact from the foreign key searchact id.
$user=$_SESSION['id'];
$sql ="SELECT * FROM `joinedactivities` JOIN `searchact` ON `joinedactivities.searchact id = searchact.id` WHERE `user id`=$user ";
$result = mysqli_query($conn, $sql)or die("Error: ".mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// output data of each row
echo "Hobby : " . $row["searchact id"];
}
} else {
echo "You have not joined any groups";
}
Backticks enclose database objects. So you're telling the query engine that this entire thing is a single object (in this case a column):
`joinedactivities.searchact id = searchact.id`
I don't think you have a column named joinedactivities.searchact id = searchact.id, so the query is failing. (And even if you did have a column named that, it would still be an incomplete ON clause.) Enclose individual database objects in backticks:
`joinedactivities`.`searchact id` = `searchact`.`id`
Your backticks are incorrect:
`joinedactivities.searchact id = searchact.id`
^--------------------------------------------^
You've turned that entire string into a single identifier. You probably want something more like
`joinedactivities`.`searchact_id` = `searchact`.`id`
And note that NONE of those identifiers are reserved words, which means that the backticks are not necessary at all.
Your code is right but a slight mistake - Wrong backtracks. Use the code below
$user=$_SESSION['id'];
$sql ="SELECT * FROM `joinedactivities` JOIN `searchact` ON `joinedactivities`.`searchact id` = `searchact`.`id` WHERE `user id`=$user ";
$result = mysqli_query($conn, $sql)or die("Error: ".mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// output data of each row
echo "Hobby : " . $row["searchact id"];
}
} else {
echo "You have not joined any groups";
}
Hope this helps you

Categories