Copy 1 sql table to another with some additional data - php

I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?

while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

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 statement not running in PHP variable declaration

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

php visitor counter not working

I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).

i want to execute a saved query in the database

I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.

Categories