I know that is impossible to alter multiple tables at once, so I'm building my own PHP script that will do the job for me.
Here, I got all the tables that I want to alter:
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM queue LIKE '%room_%'");
while($table = mysqli_fetch_array($result)) {
echo($table[0] . "<br>");
}
?>
Now, I want to create a loop that executes a MySQL query for each table and echo a status every time each query is executed. Something like this:
<?php
foreach ($table[0] as $tableToAlter) {
$result = mysqli_query('ALTER TABLE $tableToAlter AUTO_INCREMENT = 1001');
if (!$result) {
echo 'Alter failded.';
} else {
echo 'Alter successful'
}
}
?>
As you can see, I'm a newbie in PHP and I am stuck in this last part. I don't know if I need to make an array to string conversion before the loop. If someone can please tell me how to make this works in the right way I will really appreciate. Thanks.
As suggested in the comments, you could call your query within the while loop using the variable $table[0].
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM queue LIKE '%room_%'");
while($table = mysqli_fetch_array($result)) {
echo("Altering {$table[0]}<br>");
if (!mysqli_query("ALTER TABLE {$table[0]} AUTO_INCREMENT = 1001");) {
echo 'Alter failded.';
} else {
echo 'Alter successful'
}
echo "<br>";
}
?>
As a side note, seeing as we are injecting unknown input into our query I would suggest in general using prepared statements, an example of which can be found here: How can I prevent SQL injection in PHP? (top answer)
Related
I have a table where I store all the machine details, I need to delete all data and drop all tables of a specific user.
I'm trying to DROP tables based on the result from Select query, but it's not working as it is inside WHILE of SELECT query. Kindly help me with this.
$sql="SELECT M_ID FROM machine_details WHERE Username='".$inname."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$delmid=$row['M_ID'];
$delsta=$delmid."_status";
$delpar=$delmid."_parameter";
$sql1="DROP TABLE IF EXISTS $delpar, $delsta";
if(!mysqli_query($conn,$sql1))
{
echo "Error in drop".mysqli_error($conn);
}
else
{
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
if(!mysqli_query($conn,$sql2))
{
echo "Error in machine delete".mysqli_error($conn);
}
}
I'm not getting any errors from PHP or MariaDB, but the code doesn't DROP the table(It exists in phpmyadmin).
Any alternate or more efficient methods are also welcome.
UPDATE : The above code works perfectly fine now, kindly see the edit logs for better understanding about the issue I faced.
ID is int type! Dont place it in quotes. Right method is:
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
Try with Following Code to Delete.
For Delete you can use this code.
<?php
//delete.php
include("connection.php");
if(isset($_POST["_id"]))
{
$query = "DELETE FROM app WHERE _id = '".$_POST["_id"]."'";
if(mysqli_query($connection, $query))
{
echo 'Data Deleted';
}
}
?>
Note: Don't Delete any user data from the table, because if you need any history or detail report you can use this, for this you can put one flag.
Just remove the backquotes(`)
With its use M_ID is being converted to String type. Which should not happen... Because the primary key is int in your case
DELETE FROM machine_details WHERE M_ID=".$delmid;
I'm trying to do a simple query:
SELECT
job_title,
job_description,
job_tasks,
technology_skills,
job_activities
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
It works perfectly in mysql giving me this result:
http://imgur.com/a/E9yv3
However, when I use this in my PHP it returns an empty data set. I did some troubleshooting by trying to query the columns one by one and it works(returning the correct results respectively.
SELECT
job_title, job_description, job_tasks
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
Apparently, when I try to query anything from the columns of [technology_skills] OR [job_activities], the php result would return as BLANK. Does anyone have any idea why? this is strange and im kinda new to this
This is my php code:
$query = 'SELECT job_title,job_description,job_tasks FROM careeryou_db3 WHERE Job_Interests = " CIE" ';
$resultset = mysql_query($query, $connection);
$records = array();
while($r = mysql_fetch_assoc($resultset)){
$records[] = $r;
}
echo json_encode($records);
I can't see any error on your sql syntax. Can you check the mysql logs for better error information?
See here for details
https://dev.mysql.com/doc/refman/5.7/en/error-log.html
[mysqld]
log_error=/var/log/mysql/mysql_error.log
general_log_file=/var/log/mysql/mysql.log
It would help how you call the mysql, place the query build code as example.
It might be worth adding these lines for extra debugging to ensure your connection and query is successful.
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
....
It is because of the data in those columns that are conflicting with the PHP. Apparently this "—" cannot get parse into PHP which explains why the query works only in phpMyAdmin and not my PHP script.
So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.
I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.
I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.