cannot create database using mySQLi - php

I'm always getting error when inserting the value to my database. but it's working when i'm using mySQL only, I'm new to SQLi so please be gentel.
insert.php
<?php
include("dbinfo.inc.php");
//connect to mysql server
$mysqli = new mysqli("localhost", $username, $password, $database);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
//insert
$query = "insert into client_info set (
id = '".$mysqli->real_escape_string('')."',
first = '".$mysqli->real_escape_string($_POST['first'])."',
last = '".$mysqli->real_escape_string($_POST['last'])."',
phone = '".$mysqli->real_escape_string($_POST['phone'])."',
mob = '".$mysqli->real_escape_string($_POST['mob'])."',
fax = '".$mysqli->real_escape_string($_POST['fax'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
web = '".$mysqli->real_escape_string($_POST['web'])."',
com = '".$mysqli->real_escape_string($_POST['com'])."',
address = '".$mysqli->real_escape_string($_POST['address'])."',
city = '".$mysqli->real_escape_string($_POST['city'])."',
state = '".$mysqli->real_escape_string($_POST['state'])."',
zip = '".$mysqli->real_escape_string($_POST['zip'])."',
zone = '".$mysqli->real_escape_string($_POST['zone'])."',
office = '".$mysqli->real_escape_string($_POST['office'])."',
office_num = '".$mysqli->real_escape_string($_POST['office_num'])."',
ext_mob = '".$mysqli->real_escape_string($_POST['ext_mob'])."',
ext_phone = '".$mysqli->real_escape_string($_POST['ext_phone'])."',
ext_office = '".$mysqli->real_escape_string($_POST['ext_office'])."',
srv = '".$mysqli->real_escape_string($_POST['srv'])."',
stype = '".$mysqli->real_escape_string($_POST['stype'])."',
voip = '".$mysqli->real_escape_string($_POST['voip'])."',
vpass = '".$mysqli->real_escape_string($_POST['vpass'])."',
regDate = '".$mysqli->real_escape_string($_POST['regDate'])."',
acct = '".$mysqli->real_escape_string($_POST['acct'])."',
Nagents = '".$mysqli->real_escape_string($_POST['Nagents'])."',
agents = '".$mysqli->real_escape_string($_POST['agents'])."',
password = '".$mysqli->real_escape_string($_POST['password'])."'
)";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "User was created.";
}else{
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli->close();
?>
create.php
<html>
<head>
<title></title>
<script language="JavaScript">
var today=new Date();
var jran=today.getTime();
function random() {
ia=9301;
ic=49297;
im=233280;
jran = (jran*ia+ic) % im;
return jran/(im*1.0);
};
function rand(number) {
return Math.ceil(random()*number);
};
function makearray(n) {
this.length = n;
for (var i = 1; i <= n; i++) this[i] = 0;
return this;
}
var asciitable = new makearray (128);
asciitable.length=128;
for (var i=0;i<=127;i++) asciitable[i]="";
asciitable[33]="!"; asciitable[34]="\"";
asciitable[35]="#"; asciitable[36]="$";
asciitable[37]="%"; asciitable[38]="&";
asciitable[39]="'"; asciitable[40]="(";
asciitable[41]=")"; asciitable[42]="*";
asciitable[43]="+"; asciitable[44]=",";
asciitable[45]="-"; asciitable[46]=".";
asciitable[47]="/"; asciitable[48]="0";
asciitable[49]="1"; asciitable[50]="2";
asciitable[51]="3"; asciitable[52]="4";
asciitable[53]="5"; asciitable[54]="6";
asciitable[55]="7"; asciitable[56]="8";
asciitable[57]="9"; asciitable[58]=":";
asciitable[59]=";"; asciitable[60]="<";
asciitable[61]="="; asciitable[62]=">";
asciitable[63]="?"; asciitable[64]="#";
asciitable[65]="A"; asciitable[66]="B";
asciitable[67]="C"; asciitable[68]="D";
asciitable[69]="E"; asciitable[70]="F";
asciitable[71]="G"; asciitable[72]="H";
asciitable[73]="I"; asciitable[74]="J";
asciitable[75]="K"; asciitable[76]="L";
asciitable[77]="M"; asciitable[78]="N";
asciitable[79]="O"; asciitable[80]="P";
asciitable[81]="Q"; asciitable[82]="R";
asciitable[83]="S"; asciitable[84]="T";
asciitable[85]="U"; asciitable[86]="V";
asciitable[87]="W"; asciitable[88]="X";
asciitable[89]="Y"; asciitable[90]="Z";
asciitable[91]="["; asciitable[92]="\\";
asciitable[93]="]"; asciitable[94]="^";
asciitable[95]="_"; asciitable[96]="`";
asciitable[97]="a"; asciitable[98]="b";
asciitable[99]="c"; asciitable[100]="d";
asciitable[101]="e"; asciitable[102]="f";
asciitable[103]="g"; asciitable[104]="h";
asciitable[105]="i"; asciitable[106]="j";
asciitable[107]="k"; asciitable[108]="l";
asciitable[109]="m"; asciitable[110]="n";
asciitable[111]="o"; asciitable[112]="p";
asciitable[113]="q"; asciitable[114]="r";
asciitable[115]="s"; asciitable[116]="t";
asciitable[117]="u"; asciitable[118]="v";
asciitable[119]="w"; asciitable[120]="x";
asciitable[121]="y"; asciitable[122]="z";
asciitable[123]="{"; asciitable[124]="|";
asciitable[125]="}"; asciitable[126]="~";
function nchar(num) {
if ((num>=33) && (num<=127)) return asciitable[num];
}
function doit() {
var i;
var n;
var s = "";
for (i=1;i<=8;i++) {
n=0;
while ( (n<=47) ||
((n>=58) && (n<=96)) ||
(n>=123)) n = rand(126);
s = s + nchar(n);
}
document.gen.password.value = s;
}
</script>
</head>
<body>
<form method="post" action="insert.php" name="gen">
<b>Personal Info:</b>
<p>First Name:<input type="text" name="first" size="20" /></p>
<p>Last Name:<input type="text" name="last" size="20" /></p>
<p>Mob:<input type="text" name="mob" size="20" />
ext:<input type="text" name="ext_mob" size="4" /></p>
<p>Phone:<input type="text" name="phone" size="20" />
ext:<input type="text" name="ext_phone" size="4" /></p>
<p>Fax:<input type="text" name="fax" size="20" /></p>
<p>E-mail:<input type="text" name="email" size="35" />
<p>Address:<input type="text" name="address" size="40" /></p>
<p>City:<input type="text" name="city" size="20" /></p>
<p>State:<input type="text" name="state" size="20" /></p>
<p>Zip Code:<input type="text" name="zip" size="5" /></p>
<p>Zone:<input type="text" name="zone" size="5" /></p>
<br>
<b>Office Info:</b>
<p>Company:<input type="text" name="com" size="40" /></p>
<p>Office Address:<input type="text" name="office" size="40" /></p>
<p>Office Num #:<input type="text" name="office_num" size="15" />
ext:<input type="text" name="ext_office" size="4" /></p>
<p>Website:<input type="text" name="web" size="30" /></p><br>
<b>Account Info:</b>
<p>Registry Date:<input type="text" name="regDate" size="30" /></p>
<p>Account:<input type="text" name="acct" size="20" /></p>
<p>Service:<input type="text" name="srv" size="15" /></p>
<p>Service Type:<input type="text" name="stype" size="40" /></p>
<p>Number of Agents:<input type="text" name="Nagents" size="3" /></p><br>
<b>Agent Info:</b>
<p>Agents:<input type="text" name="agents" size="40" /></p>
<p>VOID:<input type="text" name="voip" size="20" /></p>
<p>VOIP Password:<input type="text" name="vpass" size="20" /></p>
<br>
<input type="hidden" size="20" name="password">
<input type="submit" name="go" value="Insert to Database" onclick="doit()">
</form>
</body>
</html>
the error i get is when the scripts tries to insert the query to the DB
"Database Error: Unable to create record."
i tried to see if there are any output on my form, and there is, even tried to insert just one variable "first" still getting errors, don't know what I'm doing wrong here

If you are using SET syntax in INSERT statement, you should not use parenthesis around it.
-- One way to insert
INSERT INTO table SET col1 = 'val1', col2 = 'val2';
-- other way
INSERT INTO table(col1,col2) VALUES('val1','val2');
Also use native errors provided by the driver to see what's wrong with your query

Related

Required field in a form

i have a simple form and i need that some fields are required.
I do not understand why they do not work. In fact, if I click on the Send button, it takes me to an error page.
I have tried inserting both the required = "required" and only required.
How can I do according to you?
Thank you for your time and availability.
<h3> Dati Prenotazione</h3>
 Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
 Nominativo:<br> <input type="text" name="nominativo" placeholder="Nome Cognome" size="20" required="required"><br>
 Email: <br>  <input type="email" name="email" size="20" placeholder="email" required><br>
 Oggetto Conferenza:<br> <textarea name="oggetto" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza" required></textarea><br>
 Data: <br> <input type="date" name="data" required ><br>
 Orario Inizio: <br> <input type="time" name="orario_inizio" min="09:30:00" max="16:30:00" required ><br>
 Orario Fine: <br> <input type="time" name="orario_fine" min="10:00:00" max="18:30:00" required><br>
<br>
<b> Partecipanti Interni </b>
<br>
<br>
<div id="interni">
<div id="first">
 Nominativo:<br> <textarea name="nominativoi" rows="5" cols="30" placeholder="Nome Cognome;" required ></textarea><br>
 Email:<br>  <textarea name="emaili" rows="5" cols="30" placeholder="Inserire Email" required></textarea><br>
input.php
require ('config.php');
// Richiedente
$nominativo = $_POST['nominativo'];
$email = $_POST['email'];
$oggetto = $_POST['oggetto'];
$data = $_POST['data'];
$orario_inizio = $_POST['orario_inizio'];
$orario_fine = $_POST['orario_fine'];
$stanza = 0;
// Personale Interno
$nominativoi = $_POST['nominativoi'];
$emaili = $_POST['emaili'];
// Persona Esterno
$nominativoe = $_POST['nominativoe'];
$emaile = $_POST['emaile'];
//aggiunta di un'ora ( per tornare indietro cambiare $newTimeEnd con $orario_fine
$dateTime = DateTime::createFromFormat('H:i', $orario_fine);
$dateInterval = DateInterval::createFromDateString('1 hour');
$dateTime->add($dateInterval);
$query1 = "INSERT INTO prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',1)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
else if ($prenotato == 1 AND $prenotatoaccettato == 0 ){
$query1 = "INSERT INTO prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',2)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
EDIT.
When i click submit the error is
Fatal error: Uncaught Error: Call to a member function add() on boolean
( about $dateTime->add($dateInterval); )
check required fields in your code
if (empty($_POST["nominativo"])) {
addError('nominativo','nominativo error text');
} else {
$nominativo = $_POST["nominativo"];
}
Nome Cognome : <input type="text" name="nominativo">
<span class="error">* <?php echo $nominativoErr;?></span>
Isn't you problem rather in the input.php (can you post it ?) ? Are you sure of the path ?
Also, don't trust what is sent, make a validation in your php too, the HTML and JS code can be changed by the user.
you can try something like:
if($email==NULL|$data==NULL) {
?>
<script>
alert("Missing Fields!");
location.href="form1.html";// page where ir your form
</script>
<?php
}
if (!preg_match("/^[a-zA-Z0-9_\.\-]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $email)) {
exit('The email format is incorrect.');
}

Display data into text box

I'm new in working on PHP. My little project works on display first and last name of student, according to h/is/er id.
index page should have 3 text box:
student id
first name
last name
when inserting student id in the first text box and press enter key, related information must appear in the other two boxes(first and last name).
Code in validation.php:
$con = new mysqli('localhost', 'root', '', 'db_sars') or die(mysqli_error());
$student_no = $_GET['student_no'];
$query = "SELECT student_no,firstname,lastname FROM student WHERE student_no = '$student_no'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result)<1) {
echo "<span class='green'>Available</span>";
}
else{
$followingdata = $result->fetch_assoc();
echo $followingdata["firstname"].'<br />';
echo $followingdata["lastname"].'<br />';
}
index.html contains ajax script and text boxes:
</br><input type="text" name="student_no" id="student_no" placeholder="Enter student #"></div></br>
<input type="text" name="firstname" id="firstname" >
<input type="text" name="lastname" id="lastname" >
A basic approach: Since the page reloads when you submit the form, you could simply populate the values of the inputs when you load the page by storing your values rather than echo-ing them:
PHP:
$first = $followingdata["firstname"];
$last = $followingdata["lastname"];
HTML:
<input type="text" name="firstname" id="firstname" value="<? echo $first ?>">
<input type="text" name="lastname" id="lastname" value="<? echo $last ?>">
php
$followingdata = $result->fetch_assoc();
$first_name = $followingdata["firstname"];
$last_name = $followingdata["lastname"];
echo json_encode(array(
'first' = $first_name,
'last' = $last_name,
));
your ajax succeed callback function
function (data) {
obj = JSON.parse(data);
if (obj) {
var first = obj.first;
var last = obj.last;
document.getElementById('firstname').value = first;
document.getElementById('lastname').value = last;
}
}
html
<input type="text" name="student_no" id="student_no" placeholder="Enter student #"></div>
<input type="text" name="firstname" id="firstname" >
<input type="text" name="lastname" id="lastname" >

Incorrect error showing up when trying to use PHP to enter info into a MySQL database?

I'm trying to create a PHP script to connect an HTML form to a MySQL database, and everything is working except there is one input that cannot be null, and no matter what I do, the system doesn't seem to recognize when I enter text into the field, and I have no idea what I'm doing wrong.
Here's my PHP code:
if (empty($_POST['book_name']))
{$errors[ ] = 'You forgot to enter the book name.';
}
else {
$booktitle = trim($_POST['book_name']);
}
if (empty($_POST['author']))
{$errors[ ] = 'You forgot to enter the author.';
}
else {
$author = trim($_POST['author']);
}
if (empty($_POST['cover']))
{$errors[ ] = 'You forgot to enter the book cover image.';
}
else {
$cover = trim($_POST['cover']);
}
if (empty($_POST['publisher']))
{$errors[ ] = 'You forgot to enter the publisher.';
}
else {
$publisher = trim($_POST['publisher']);
}
if (empty($_POST['language_id']))
{$errors[ ] = 'You forgot to enter the book language.';
}
else {
$languageid = trim($_POST['language_id']);
}
if (empty($_POST['length_pages']))
{$errors[ ] = 'You forgot to enter the book length in pages.';
}
else {
$lengthpages = trim($_POST['length_pages']);
}
if (empty($_POST['fiction']))
{$errors[ ] = 'You forgot to enter if the book is fiction or not.';
}
else {
$fiction = trim($_POST['fiction']);
}
if (empty($_POST['pub_year']))
{$errors[ ] = 'You forgot to enter the year the book was published.';}
else {
$pubyear = trim($_POST['pub_year']);
}
if (empty($errors)) {
require ('mysqli_connect.php');
}
$q = "INSERT INTO books(book_name, author, publisher, language_id, length_pages, cover, fiction, pub_year) VALUES
('$booktitle', '$author', '$publisher', '$languageid', '$lengthpages', '$cover', '$fiction', '$pubyear')";
$r = #mysqli_query($dbc, $q);
if ($r) {
echo 'Thank you! This book information has been entered into the database.';
}
else {
echo 'System error.';
echo mysqli_error($dbc) . ' Query: ' . $q;
foreach ($errors as $msg) {
echo " - $msg<br>\n";
}
}
?>
and here's my HTML code:
<form action="register.php" method="post">
<p>Book name: <input type="text" name="book_name" size="20" maxlength="100" value="<?php if (isset($_POST['book_name'])) echo $_POST['book_name']; ?>" /></p>
<p>Author: <input type="text" name="author" size="20" maxlength="100" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Publisher: <input type="text" name="publisher" size="20" maxlength="100" value="<?php if (isset($_POST['publisher'])) echo $_POST['publisher']; ?>" /></p>
<p>Language:</p>
<p>English <input type="radio" name="language_id" value="1" /></p>
<p>Spanish <input type="radio" name="language_id" value="2" /></p>
<p>French <input type="radio" name="language_id" value="3" /></p>
<p>Italian <input type="radio" name="language_id" value="4" /></p>
<p>Mandarin <input type="radio" name="language_id" value="5" /></p>
<p>Number of pages: <input type="text" name="length_pages" size="20" maxlength="100" value="<?php if (isset($_POST['length_pages'])) echo $_POST['length_pages']; ?>" /></p>
<p>Cover image file name: <input type="text" name="cover" size="20" maxlength="100" value="<?php if (isset($_POST['cover'])) echo $_POST['cover']; ?>" /></p>
<p>Is this book fiction?:</p>
<p>Yes <input type="radio" name="fiction" value="yes" /></p>
<p>No <input type="radio" name="fiction" value="no" /></p>
<p>Year Published: <input type="text" name="pub_year" size="20" maxlength="100" value="<?php if (isset($_POST['pub_year'])) echo $_POST['pub_year']; ?>" /></p>
<input type="submit" name="submit" value="submit" /></form>
And for whatever reason, every time I try to test it out, I get this error message:
"System error. Query: INSERT INTO books(book_name, author, publisher, language_id, length_pages, cover, fiction, pub_year) VALUES ('', 'Not Hayley Munguia', 'Random House', '2', '134', 'howtobenormal.jpg', 'no', '1938') - You forgot to enter the book name."
even though I'm definitely inputting something into the book name field.
I really have no idea what I'm doing wrong, all help is appreciated! Thank you!
First check taking the sentences the mysql and put directly in the phpmyadmin and see the errors. Second I can see is likely the var book_name is empty

MySQL database not updating

output from the database seems fine, but input from the update doesn't pass onto the database
edit.php - from here all values displays correctly
<?php
session_start();
$name = $_SESSION['name'];
$sur = $_SESSION['sur'];
$pass = $_SESSION['pass'];
echo $name.' '.$sur.' '.$pass;
//connect
$dbh = mysql_connect ("localhost", "xxx_admin", "xxx")
or die ('ERROR!');
mysql_select_db ("xxx_database");
$query="SELECT * FROM client_info WHERE (first='$name' AND last='$sur' AND password='$pass')";
$result=mysql_query($query);
$id = mysql_result($result,$i,"id");
$first = mysql_result($result,$i,"first");
$last = mysql_result($result,$i,"last");
$phone = mysql_result($result,$i,"phone");
$mob = mysql_result($result,$i,"mob");
$fax = mysql_result($result,$i,"fax");
$email = mysql_result($result,$i,"email");
$web = mysql_result($result,$i,"web");
$com = mysql_result($result,$i,"com");
$add = mysql_result($result,$i,"add");
$city = mysql_result($result,$i,"city");
$state = mysql_result($result,$i,"state");
$zip = mysql_result($result,$i,"zip");
$zone = mysql_result($result,$i,"zone");
$office = mysql_result($result,$i,"office");
$office_num = mysql_result($result,$i,"office_num");
$ext_mob = mysql_result($result,$i,"ext_mob");
$ext_phone = mysql_result($result,$i,"ext_phone");
$ext_office = mysql_result($result,$i,"ext_office");
$srv = mysql_result($result,$i,"srv");
$stype = mysql_result($result,$i,"stype");
$voip = mysql_result($result,$i,"voip");
$vpass = mysql_result($result,$i,"vpass");
$regDate = mysql_result($result,$i,"regDate");
$acct = mysql_result($result,$i,"acct");
$Nagent = mysql_result($result,$i,"Nagent");
$agents = mysql_result($result,$i,"agents");
$password = mysql_result($result,$i,"password");
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="update.php" name="gen">
<b>Personal Info:</b>
<p>First Name:<input type="text" name="first" size="20" value="<?php echo $first; ?>"/></p>
<p>Last Name:<input type="text" name="last" size="20" value="<?php echo $last; ?>"/></p>
<p>Mob:<input type="text" name="mob" size="20" value="<?php echo $mob; ?>"/>
ext:<input type="text" name="ext_mob" size="4" value="<?php echo $ext_mob; ?>"/></p>
<p>Phone:<input type="text" name="phone" size="20" value="<?php echo $phone; ?>"/>
ext:<input type="text" name="ext_phone" size="4" value="<?php echo $ext_phone; ?>"/></p>
<p>Fax:<input type="text" name="fax" size="20" value="<?php echo $fax; ?>"/></p>
<p>E-mail:<input type="text" name="email" size="35" value="<?php echo $email; ?>"/></p>
<p>Address:<input type="text" name="add" size="40" value="<?php echo $add; ?>"/></p>
<p>City:<input type="text" name="city" size="20" value="<?php echo $city; ?>"/></p>
<p>State:<input type="text" name="state" size="20" value="<?php echo $state; ?>"/></p>
<p>Zip Code:<input type="text" name="zip" size="5" value="<?php echo $zip; ?>"/></p>
<p>Zone:<input type="text" name="zone" size="5" value="<?php echo $zone; ?>"/></p>
<br>
<b>Office Info:</b>
<p>Company:<input type="text" name="com" size="40" value="<?php echo $com; ?>"/></p>
<p>Office Address:<input type="text" name="office" size="40" value="<?php echo $office; ?>"/></p>
<p>Office Num #:<input type="text" name="office_num" size="15" value="<?php echo $office_num; ?>"/>
ext:<input type="text" name="ext_office" size="4" value="<?php echo $ext_office; ?>"/></p>
<p>Website:<input type="text" name="web" size="30" value="<?php echo $web; ?>"/></p><br>
Old password:
<input type="password" size="20" name="oldpassword">
New password:
<input type="password" size="20" name="newpassword">
verify new password
<input type="password" size="20" name="verpassword">
<input type="text" size="20" name="id" value="<?php echo $id; ?>">
<input type="submit" value="Update Database">
</form>
</body>
</html>
update.php - it says update success , but there are no changes on my database
<?php
session_start();
$ud_id=$_POST['id'];
$name = $_SESSION['name'];
$sur = $_SESSION['sur'];
$pass = $_SESSION['pass'];
$ud_first = $_POST['first'];
$ud_last = $_POST['last'];
$ud_phone = $_POST['phone'];
$ud_mob = $_POST['mob'];
$ud_fax = $_POST['fax'];
$ud_email = $_POST['email'];
$ud_web = $_POST['web'];
$ud_com = $_POST['com'];
$ud_add = $_POST['add'];
$ud_city = $_POST['city'];
$ud_state = $_POST['state'];
$ud_zip = $_POST['zip'];
$ud_zone = $_POST['zone'];
$ud_office = $_POST['office'];
$ud_office_num = $_POST['office_num'];
$ud_ext_mob = $_POST['ext_mob'];
$ud_ext_phone = $_POST['ext_phone'];
$ud_ext_office = $_POST['ext_office'];
$ud_password = $_POST['newpassword'];
//connect
$dbh = mysql_connect ("localhost", "xxx_admin", "xxx")
or die ('ERROR!');
mysql_select_db ("xxx_database");
$query="UPDATE client_info SET first='$ud_first',last='$ud_last',phone='$ud_phone',mob='$ud_mob',fax='$ud_fax',email='$ud_email',web='$ud_web',com='$ud_com',add='$ud_add',city='$ud_city',state='$ud_state',zip='$ud_zip',zone='$ud_zone',office='$ud_office',office_num='$ud_office_num',ext_mob='$ud_ext_mob',ext_phone='$ud_ext_phone',ext_office='$ud_ext_office',password='$ud_password' WHERE id='$ud_id'";
mysql_query($query);
echo "Record Updated at ID: ".$ud_id;
mysql_close();
?>
As I don't know your table structure, Try this and debug accordingly.
$query="UPDATE client_info SET first='$ud_first',
last='$ud_last',
phone='$ud_phone',
mob='$ud_mob',
fax='$ud_fax',
email='$ud_email',
web='$ud_web',
com='$ud_com',
add='$ud_add',
city='$ud_city',
state='$ud_state',
zip='$ud_zip',
zone='$ud_zone',
office='$ud_office',
office_num='$ud_office_num',
ext_mob='$ud_ext_mob',
ext_phone='$ud_ext_phone',
ext_office='$ud_ext_office',
password='$ud_password' WHERE id=$ud_id;";
mysql_query($query) or die(mysql_error());
of all i STRONGLY suggest you escape your user input before sending anything to the DB. it will escape special charaters and pevent use of keywords to mess your db. to do so, simply use mysql_real_escape_string() like so;
$ud_first = mysql_real_escape_string($_POST['first']);
You sould check mysqli as mysql being decretated. If your just starting your code, i usggest you switch as soon as possible. Efficiency and security will increase.
Add an ; at the end of you query. Will help the server to know where it ends.
change or die ('ERROR!'); by or die (mysql_error()); This will echo the last error encourtered by mysql server. It will most likely tell you what your probelm is.
I give you those hints as i don't see why your code don't work as expected.
Something out of the range of this question but why assign each of the result values separately?
You expect one result and as $i not set is actually null it works
maybe you could simplify your life and code by using
$r = mysql_fetch_assoc($result);
foreach($r as $key=>$value){ $$key=$value; }
If there would be more rows expected or possible, you would have to close it in a foreach loop or similar solution. Other side, processing the post and securing input may be short&simple too
$allowed_post_vars=array('city','zip',...); // define ok variables
foreach($allowed_post_vars as $postvar)// each of them
{ $ud='ud_'.$postvar; // prepare longer name, like $ud_city etc
$$ud=mysql_real_escape_string($_POST[$postvar]); //assign it sanitized value
}

MySQL Syntax Error at long entered text

I am trying to build a PHP Form with MySQL. The problem is that I get an error every time if I try to add some long Text into the field.
The error
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.....at line 1
The PHP code generating the query is this:
<?php
if ( $_GET['aktion'] == "speichern" )
{
$title = $_GET['title'];
$description = $_GET['description'];
$applepart = $_GET['applepart'];
$partnumber = $_GET['partnumber'];
$productcode = $_GET['productcode'];
$compatibility = $_GET['compatibility'];
$url_bild = $_GET['url_bild'];
$price = $_GET['price'];
$sql = "INSERT INTO adressbuch ";
$sql .= " SET ";
$sql .= " title = '$title', ";
$sql .= " description = '$description', ";
$sql .= " applepart = '$applepart', ";
$sql .= " partnumber = '$partnumber', ";
$sql .= " productcode = '$productcode', ";
$sql .= " compatibility = '$compatibility', ";
$sql .= " url_bild = '$url_bild', ";
$sql .= " price = '$price' ";
require_once ('konfiguration.php');
$db_erg = mysql_query($sql)
or die("Anfrage fehlgeschlagen: " . mysql_error());
echo '<h1>Adresse wurde speichert</h1>';
echo 'Auflistung anzeigen';
exit;
}
?>
<form name="" action="" method="GET" enctype="text/html">
<p>Title:<br />
<input type="text" name="title" value="" size="60" />
</p>
<p>description:<br />
<input type="text" name="description" value="" size="60" />
</p>
<p>applepart:<br />
<input type="text" name="applepart" value="" size="60" />
</p>
<p>partnumber:<br />
<input type="text" name="partnumber" value="" size="60" />
</p>
<p>productcode:<br />
<input type="text" name="productcode" value="" size="60" />
</p>
<p>compatibility:<br />
<input type="text" name="compatibility" value="" size="60" />
</p>
<p>Bild:<br />
<input type="text" name="url_bild" value="" size="60" />
</p>
<p>price:<br />
<input type="text" name="price" value="" size="60" />
</p>
<input type="hidden" name="aktion" value="speichern" />
<input type="Submit" name="" value="speichern" />
</form>
Thanks for your help
Your code is susceptible to SQL injection, and your problem is only a hint as to why.
The rule we always use is: "Never trust data from the user-agent" (i.e. consider anything in $_GET or $_POST as potentially problematic or worse). At a minimum, we should always escape these values using mysqli_real_escape_string or else a more robust DB framework.
Your problem is that when you have long enough input, it has a single quote in it somewhere, or a newline. You can't simply concatenate user input like this and expect it to work. Worse, you are wide-open for SQL injection attacks. Find the right way to use your framework to build SQL queries.
Regardless of the SQL injection vulnerability, it seems like you are sending a query which is too long for MySQL to handle.
You can try to overcome this by changing some configuration: try and raise the parameter "max_allowed_packet" in your MySQL's configuration file. For example:
[mysqld]
max_allowed_packet = 64M
This will set it to 64MB, which means the longest single query you will be allowed to issue is 64MB, and the longest single row you will be able to retriever from a query is 64MB in size.
<?php
require_once ('konfiguration.php');
if(isset($_POST['title']))
{
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$applepart = mysql_real_escape_string(htmlspecialchars($_POST['applepart']));
$partnumber = mysql_real_escape_string(htmlspecialchars($_POST['partnumber']));
$productcode = mysql_real_escape_string(htmlspecialchars($_POST['productcode']));
$compatibility = mysql_real_escape_string(htmlspecialchars($_POST['compatibility']));
$url_bild = mysql_real_escape_string(htmlspecialchars($_POST['url_bild']));
$price = mysql_real_escape_string(htmlspecialchars($_POST['price']));
$insert = mysql_query("INSERT INTO `adressbuch` (`title`,`description`,`applepart`,`partnumber`,`productcode`,`compatibility`,`url_bild`,`price`) VALUES ('$title','$description','$applepart','$partnumber','$productcode','$compatibility','$url_bild','$price')");
if (!$insert)
{
die('Eintrag konnte nicht gespeichert werden: ' . mysql_error());
}
}
?>
<form method="POST" action="?page= ">
<span>Neuer Gästebucheintrag verfassen:</span> <br />
<span>Title</span><input type="text" name="title" /> <br />
<span>Description</span><textarea cols="16" rows="5" name="description"></textarea> <br />
<span>Apple Part</span><input type="text" name="applepart" /> <br />
<span>Part Number</span><input type="text" name="partnumber" /> <br />
<span>Product Code</span><input type="text" name="productcode" /> <br />
<span>Compatibility</span><input type="text" name="compatibility" /> <br />
<span>Image</span><input type="text" name="url_bild" /> <br />
<span>Price</span><input type="text" name="price" /> <br />
<input type="submit" value="Speichern"/> <br />
</form>

Categories