i'm using php to make some mods on my database, i have two identical tables and i want to move one row from the first table to the second one how can i do that using pure php and mysql.
that is how my tables looks like
CREATE TABLE users (
username varchar(30) primary key,
password varchar(32),
userid varchar(32),
userlevel tinyint(1) unsigned not null,
email varchar(50),
timestamp int(11) unsigned not null
);
and here is my php code so far
function procMoveUser(){
global $session, $database, $form;
/* Username error checking */
$subuser = $this->checkUsername("user");
/* Errors exist, have user correct them */
if($form->num_errors > 0){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
/* move the user */
else{
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONT."VALUES ($array['user'], $array['password'], $array['userid'] , $array['userlevel'] , $array['email'] , $array['timestamp'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
}
}
First, SELECT * FROM the first table for the row that you want to move. Then, as suggested above, run an INSERT statement with the values from the first table.
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
$result = $mysqli->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO second_table VALUES ($array['user'], $array['something'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
}
}
}
Maybe this will help: Copy an existing MySQL table to a new table
Related
I'm currently working on a PHP/MySQL ranking system, but I've come into a problem with my CREATE TABLE statement.
Here's my code:
mysql_select_db("DB1");
$numrows = "SELECT COUNT( * ) FROM information_schema.tables WHERE table_schema = 'DB1'";
if($numrows > 1){
if($numrows > 2){
$table = rand(1, $numrows);
}else{
$table = rand(1, 2);
}
}else{
$table = rand(1, 1);
}
$checkForTable = mysql_query("SELECT 1 FROM $table LIMIT 1");
if($checkForTable){
$query = "INSERT INTO $table (name,score) VALUES($name, $score)";
$result = mysql_query($query);
mysql_select_db("DB2");
$query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
$result2 = mysql_query($query2);
mysql_select_db("DB1");
if($result && $result2){
echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
}else{
echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
}
}else{
$newtable = "CREATE TABLE $table (
id bigint AUTO_INCREMENT NOT NULL,
name varchar(255) NOT NULL,
score bigint(20) NOT NULL,
PRIMARY KEY('id')
)";
$result = mysql_query($newtable);
if($result){
$query = "INSERT INTO $newtable (name,score) VALUES($name,$score)";
$result = mysql_query($query);
mysql_select_db("DB2");
$query2 = "INSERT INTO Leaderboard (name,score) VALUES($name, $score)";
$result2 = mysql_query($query2);
mysql_select_db("DB1");
if($result && $result2){
echo "<h4 style='color:green;'>Your Score Has Been Inserted</h4><hr/>";
}else{
echo "<h4 style='color:red;'>We encountered an error while inserting your data </h4><hr/>";
}
}else{
echo "TableNotCreatedException: " . mysql_error();
}
}
When I try out the code I get:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 ( id bigint AUTO_INCREMENT NOT NULL, name varcha' at line 1
I've been trying to figure this out for a while but I've had no luck. Please Help!
That's because your $table variable contains a value 1 which you are using as table name and so your query becomes
CREATE TABLE 1(....
Per MySQL Documentation it says
Identifiers may begin with a digit but unless quoted may not consist
solely of digits.
Also, your quoting the column name as seen below
PRIMARY KEY('id')
It should rather be
PRIMARY KEY(`id`)
I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).
I'm having one error when I try to use my function and I don't know how can I fix it.
function is_valid($email_e, $email_code_e, $username_e) {
$email = mysql_real_escape_string($email_e);
$email_code = mysql_real_escape_string($email_code_e);
$username = sanitize($username_e);
return (mysql_result
(mysql_query
("SELECT COUNT(*) FROM `users`
WHERE `username` = $username
AND `email_code` = $email_code
AND `email` = $email"), 0) == 1) ? true : false;
}
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /home/meuts3/public_html/core/functions/users.php on line 34
I'm trying to make a forget password system and when someone try to get a new password, he receives a link with email_code, username and email. When he clicks, he goes to a changepassword page, in this page, I will check if these information is valid using the function is_valid, so if is_valid I have to return the user_id to start a session user_id.
How can I do that?
Thanks, I really appreciate you guys.
You have an error in sql statement. You must quote $username, $email_code & $email in ''.
SELECT COUNT(*) FROM `users` WHERE `username` = '$username' AND `email_code` = '$email_code' AND `email` = '$email'
So mysql_query returns false, not a resource object.
Try this:
function is_valid($email_e,$email_code_e,$username_e) {
$email = mysql_real_escape_string($email_e);
$email_code = mysql_real_escape_string($email_code_e);
$username = sanitize($username_e);
$sql = "SELECT user_id FROM `users`
WHERE `username` = $username
AND `email_code` = $email_code
AND `email` = $email";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 0)
return -1;
return mysql_result($result,1);
}
first, avoid mysql_* functions as they're deprecated.
second,
the process should be like,
we select the user_id
If number of rows fetched is 0 then no such user else we get a unique user_id
so let's write the sql considering your column name for user_id is user_id and user_id is always>0:
$q = "SELECT user_id FROM `users` WHERE `username` = '$username' AND `email_code` = '$email_code' AND `email` = '$email'";
$r = mysql_query($q); //warning I don't like mysql_* functions
if(mysql_num_rows($r)>0){ //we have got more than 0 rows
$d = mysql_fetch_assoc($r);
return $d['user_id'];
} else { // No such username, email, email_code combination found in database
return 0;
}
Im trying to create something that if a user choses a match is going to win and that match wins the points enter automatically into DB .. Im doing fine untill the point that points enter only one time into DB. I mean validating properly but everytime on refresh points enter into DB . Help Please.
//Ndeshjet e fituara ose jo
echo "<h3>Ndeshjet e vendosura nga <b>$username</b> dhe Rezultatet:</h3><br/>";
$query = $db-> query("SELECT * FROM match_select WHERE user_id='$username'");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
if($match->rowCount($match)){
echo "";
}else{
if ($row['result'] == $row['final']){
$hey = "style='color: green;' ";
$match = $db -> query("INSERT INTO winner (user_id, match_id, koef, final, liga) VALUES ('$username','$id', '$koeficent', '1', '$liga')");
}else if ($row['final']== ""){
$hey = "style='color: black;' ";
}else{
$hey = "style='color: red;' ";
}
}
}
In respect to the code provided and as I understand it;
Select all the matches for that username (loop through all matches)
Validation: check if this has been added to the winner table already
If so ignore it, otherwise if result = final is same (don't know the context here) then store..
The problem is when you select data for validation, they are null value you should declare them before query...as here
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
it should be
$id = $row['match_id'];
$liga = $row['liga'];
$koeficent = $row['selected_koef'];
$match = $db->query("SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'");
This coluld be the reason when refereshing everytime it doesn't find any results so inserts.... my recommendation is to have SQL in a different variable and for testing purposes you can dump it on screen such as
$sql = "SELECT * FROM `winner` WHERE `user_id` = '$username' AND `match_id` = '$id' AND `liga`='$liga'";
echo $sql; //to see whats going on
$match = $db->query($sql);
Hope this helps mate
I'm using the functions below. When I register a user, the hash seems to work fine. When I try to login the hash doesn't match. It has the correct hash, plus extra hash.
What's the issue?
function salt($pass){
$salt = 'hello';
return hash('sha512', $pass.$salt);
}
function valid_credentials($user,$pass) {
$user = mysql_real_escape_string($user);
$pass = salt($pass);
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '{$pass}' ");
return (mysql_result($total, 0) == '1' ) ? true : false;
}
function add_user($user, $pass) {
$user = mysql_real_escape_string(htmlentities($user));
$pass = salt($pass);
$time = now();
mysql_query("INSERT INTO `users` ( user_name, password, date_created ) VALUES ( '{$user}', '{$pass}', '{$time}' )");
}
I think in your validation code this line:
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '{$pass}' ");
needs to be changed to something like so:
$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '".$user."' AND `password` = '".$pass."' ");
Right now it appears to be checking for the password column being equal to "{$pass}".
just double check your value returned before and after inserting the value to db table. Echo it with a trim function. or use strcmp to check the values that is inserted in the db with your generated value.