update query for unique column - php

This query change only the name, I want change the username too...
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, name VARCHAR(50) NULL, PRIMARY KEY (id), UNIQUE(username)) ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
$mysqli->close();
?>
In this example:
Started as [1, user1, name1]
Changed to [1, user1, name_1]
Instead of [1, user_1, name_1]
There is no way to update UNIQUE columns?

Your script won't run (table creation) when reloading it (only on the first/initial execution), since your table already exists and MySQL is failing on you silently, since you're not checking for errors.
Sidenote: You may have slightly modified your script and then ran it after.
Having included the following debugging code at the top of your script, you would have been thrown errors about it and is crucial when debugging during development before going live:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Therefore, you can only run that script once. You need to either test it again with a new table name, or remove the table creation code.
You can also check if the table exists.
References:
http://dev.mysql.com/doc/refman/5.7/en/create-table.html
https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html
A quick example:
CREATE TABLE IF NOT EXISTS `test`
You can also use UPDATE IGNORE table ... syntax (not to be used with your present table creation codes though):
http://dev.mysql.com/doc/refman/5.7/en/update.html
and INSERT IGNORE INTO table
https://dev.mysql.com/doc/refman/5.5/en/insert.html
Now your entire code (as a rewrite) would look like this:
$query = "CREATE TABLE IF NOT EXISTS users
(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
name VARCHAR(50) NULL,
PRIMARY KEY (id),
UNIQUE(username))
ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT IGNORE INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE IGNORE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
There is no way to update UNIQUE columns?
Yes, with UPDATE IGNORE table ....
http://dev.mysql.com/doc/refman/5.7/en/update.html
However and with your present code, it will fail on the INSERT, since that is being executed before the UPDATE.
Think logically and you will see what is going on here.

Related

cant store session variable into database

I have in seassion stored variable. I want to insert session variable and other informations filled through form into table. I got message that it was created but nothing shows in table.
I want to take session variable and store it into "username"
i tried $username=$r['username']; but doesnt work.
<?php
session_start();
if($_SESSION['user']==''){
header("Location:login.php");
}else{
$dbh=new PDO('mysql:dbname=mydb;host=127.0.0.1', 'myusername', 'mypassword');
$sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
$sql->execute(array($_SESSION['user']));
while($r=$sql->fetch()){
$username=$r['username']; <-im not sure if this is correct.
$ime=$_POST['ime'];
$priimek=$_POST['priimek'];
$email=$_POST['email'];
$izob=$_POST['izob'];
$izk=$_POST['izk'];
$prib=$_POST['prib'];
$opis=$_POST['opis'];
$sql = "INSERT INTO profil (ime, priimek, email, izob, izk, prib, opis) VALUES( `username`,`ime` , `priimek ` , `email` , `izob` , `izk` , `prib` , `opis`)";
try {
$dbh->exec($sql);
echo " created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;
}
?>
CREATE TABLE profil(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(10),
ime VARCHAR(10) NOT NULL,
priimek VARCHAR(10) NOT NULL,
email VARCHAR(20),
izob VARCHAR(20),
izk VARCHAR(10),
prib VARCHAR(10),
opis VARCHAR(100),
);
thanks for help
Two problems:
First, you only specified 7 column names in the insert list, but you gave 8 values. Most importantly, the column name you failed to specify was the username column, which is what you are asking about. Second, you should be using the actual PHP variables in the insert, not the column names escaped in backticks. Try the following:
$sql = "INSERT INTO profil (username, ime, priimek, email, izob, izk, prib, opis) ";
$sql = $sql . "VALUES(".$username.", ".$ime.", ".$priimek$.", ".$email.", ".$izob.", ".$izk.", ".$prib.", ".$opis.")";
remove username to your values and add backticks to insert.
it should be like this:
$sql = "INSERT INTO profil (`ime`, `priimek`, `email`, `izob`, `izk`, ``prib, `opis`) VALUES(`ime` , `priimek ` , `email` , `izob` , `izk` , `prib` , `opis`)";
Hey guys thnx for help i found soulution.
this line was wrong:
$sql= "INSERT INTO test (`column`) VALUES( '$value1' '$value2)";
Tnx guys

Inserting values into a table with a PHP-variable name

I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php

Create SQL Table and Populate it

I have a script that creates a SQL table for me as below
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name)) {
$sql = "CREATE TABLE ".$ac_system."_credits (id INT NOT NULL
AUTO_INCREMENT , PRIMARY KEY (id) , account_nr CHAR(10) , credits CHAR(10))";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
I would like to add another line/s to populate the above table with fixed information
ID - 1
Credits - 10
ACCOUNT_NR - 1
The above data is constant and doesn't need to be changed once the table is created I am not sure how to populate it in conjunction with the creation of the table. I can populate it from a seperate PHP script but need all to be done on one page
Maybe you should execute another one query just after successful table creation:
//some php code here
$insertSuccessful = true;
mysql_query( "INSERT INTO $ac_system ( account_nr, credits ) VALUES ( '1', '10' )", $sql );
// and here

Adding rows to mysql - get sorted randomly - want them on top

I have kind of a "problem" that I do not know how it happened. If I add rows to my table via php it just adds them randomly somewhere. But I want them to be added on top. Instead it justs add them all over the table.
$name = ($_GET["name"]);
$sql = "INSERT INTO $DB_Table VALUES('$name')";
$number = ($_GET["number"]);
$sql = "INSERT INTO $DB_Table VALUES('$number')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_query("INSERT INTO $DB_Table (Name,number)
VALUES ('$name','$m_yolo')");
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
There is no such thing as row ordering in a relational table. If you want them ordered, you need to use an ORDER BY clause. You can add a TIMESTAMP column, which you can sort on when you select your data: 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
Create another table but add an ID auto-increment column in it:
CREATE TABLE IF NOT EXISTS `table` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`number` int(10) NOT NULL,
PRIMARY KEY (`id`)
);
Then you can insert new rows like this:
$sql = "INSERT INTO $DB_Table (id, name,number) VALUES ('', '$name', '$number')";
Your new entries will be sorted by id then. You can order them in you select query with:
$sql = "SELECT 'name', 'number' FROM `table` ORDER BY 'id' DESC";
One remark about your code though: it is not safe to directly use the values from $_GET as you do at the beginning of your code. Try using mysql_real_escape_string() for example.

mysql update query (containing 'where' syntax) not working

I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.

Categories