I create some table(in MySQL):
create table clients
( clientid int unsigned not null auto_increment primary key,
Name char(50) not null,
SecondName char(50) not null,
address char(100) not null,
City char(30) not null
Email char(100);
I want to input datas(Name,SecondName,address,City,Email) into my database NewClientBase from webpage by filling by customer his personal data, but clientid should be generated by program:
<html>
<?php
...
// short names initialization. Taken from filling external form
$Name=$_POST['Name'];
$SecondName=$_POST['SecondName'];
$Address=$_POST['Address'];
$City=$_POST['City'];
$Email=$_POST['Email'];
$clientid=0;
if (!$Name || !$SecondName || !$Address || !$City || !$Email) {
echo "Not all data completed.<br />"
."Return and try again";
exit;
}
if (!get_magic_quotes_gpc()) {
$Name = addslashes($Name);
$SecondName = addslashes($SecondName);
$Address = addslashes($Address);
$City = addslashes($City);
$Email = doubleval($Email);
}
# $db = new mysqli('localhost', 'root', '********', 'NewClientBase');
$wynik_sprawdzania= mysqli_query($db, $sprawdzanie);
$ile_znalezionych=$wynik_sprawdzania->fetch_row();
$ilosc_pol=$wynik_sprawdzania->field_count;
.....
// a new record with the next number is calculated:
$clientid=$wynik_sprawdzania->fetch_row()+1;
....
and created a new record with this number:
$zapytanie = "insert into clients values ('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
.....
$db->close();
?>
</html>
the problem is:
if (for example) 5th record is generated and input into database like this
$zapytanie = "insert into clients values (5,'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
all record is inserted into database correctly.
but if it is inserted like this
$zapytanie = "insert into clients values
('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
($clientid No 5 is calculated programly as shown above) record is not created. Neither '".clientid."' nor '.$clientid.' Can anybody help me? Any solution exists? Thanks
ClientId is defined as Int, not as string. You try to input string. Remove the single quotes on $clientid.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
The variable $clientid should be considered as integer and should not add any quotes.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
Hope this helps
Related
I'm new to PHP, trying to update table in php when i clicked on update link it show message "Not Updated".where i went wrong?
following is the code which is executed when update link is clicked.
<?php
$servername='localhost';
$username='root';
$password='';
$dbname = "registration";
$conn=mysqli_connect($servername,$username,$password,$dbname);
$sql= 'UPDATE members_t SET Fname =$_POST[FIRSTNAME], Lname
=$_POST[LASTNAME], Memail = $_POST[EMAIL],Mcontact = $_POST[CONTACT],Mwhtap
= $_POST[WHATSAPP], Maddress = $_POST[ADDRESS], Mprofession =
$_POST[PROFESSION], WHERE id= $_POST[id]';
if(mysqli_query($conn, $sql))
header("refresh:1; url=up.php");
else
echo "Not Updated";
?>
Please execute the following script :
<?php
$servername="localhost";
$username="root";
$password="";
$dbname = "registration";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (!$conn){
die("Connection failed: " . mysqli_connect_error());
}
$firstName = $_POST["FIRSTNAME"];
$lastName = $_POST["LASTNAME"];
$email = $_POST["EMAIL"];
$contact = $_POST["CONTACT"];
$whatsapp = $_POST["WHATSAPP"];
$address = $_POST["ADDRESS"];
$profession = $_POST["PROFESSION"];
$id = $_POST["id"];
$sql= "UPDATE `members_t` SET `FIRSTNAME` = '$firstName',`LASTNAME` = '$lastName',`EMAIL` = '$email' ,`CONTACT` = $contact,`WHATSAPP` = $whatsapp, `ADDRESS` = '$address', `PROFESSION` = '$profession' WHERE id = $id";
if(mysqli_query($conn, $sql)){
header("refresh:1; url=up.php");
}else{
echo "Not Updated";
}
?>
If any error occurs then execute the sql statement in phpmyadmin or MySQL Workbench and share the error thrown(if any).
You have created a Table with the following column names : FIRSTNAME, LASTNAME , EMAIL, CONTACT, WHATSAPP,ADDRESS,PROFESSION but you're using Fname,Lname,Memail,Mcontact and so on. Also your create table query is not correct , theres a syntax error :
CREATE TABLE MEMBERS_T(id INT(6) NOT NULL PRIMARY KEY AUTO_INCREMENT, FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(30), EMAIL VARCHAR(30), CONTACT INT(20), WHATSAPP INT(20), ADDRESS VARCHAR(50), PROFESSION VARCHAR(30));
The code has been updated according to your table and should work.
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.
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
I'm new to PHP, MySQL and working on an project for my school. I need to make a form that inserts new students into a database.
I need to have an primary key named studentnummer so I can use this later on, but this needs to be created in the database table not in the form. When I try to insert the data of the form in the table I'll get an error saying I need to insert data in table row 1 (this is the primary key which is AI and an INT)
I've got the following for PHP and MySQL:
require ("connection.php");
//gets the data from the form
$voornaam = $_REQUEST['voornaam'];
$tussenvoegsel = $_REQUEST['tussenvoegsel'];
$achternaam = $_REQUEST['achternaam'];
$geboortedatum = $_REQUEST['geboortedatum'];
$woonplaats = $_REQUEST['woonplaats'];
$straat = $_REQUEST['straat'];
$huisnummer = $_REQUEST['huisnummer'];
$postcode = $_REQUEST['postcode'];
$telefoonnummer = $_REQUEST['telefoonnummer'];
$mobielnummer = $_REQUEST['mobielnummer'];
$email = $_REQUEST['email'];
$voor = $_REQUEST['voor'];
$motivatie = $_REQUEST['motivatie'];
$alt = $_REQUEST['alt'];
$tbl_name ="studenten";//db table name
$sql_ins = mysql_query("INSERT INTO $tbl_name values('??studentnummer??','$voornaam', '$tussenvoegsel', '$achternaam', '$geboortedatum', '$woonplaats', '$straat', '$huisnummer', ' $postcode' , '$telefoonnummer', '$mobielnummer', '$email', '$voor', '$motivatie', '$alt')");
This is a printscreen from my table stucture. If anyone knows what I can do about this problem I would appreciate it very much!!!
Thanks.
If you insert a NULL into an auto_increment primary key field, mysql will supply the value for you, so
INSERT INTO $tbl_name VALUES(NULL, blah blah blah)
and then you can retrieve the generated value with
$studentnummer = mysql_insert_id();
Note that you shouldn't be using the mysql_*() functions. They're deprecrated. Consider switching to mysqli or PDO
Please try this-
$sql_ins = mysql_query("INSERT INTO $tbl_name values('','$voornaam', '$tussenvoegsel', '$achternaam', '$geboortedatum', '$woonplaats', '$straat', '$huisnummer', ' $postcode' , '$telefoonnummer', '$mobielnummer', '$email', '$voor', '$motivatie', '$alt')");
I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";