Sorry, I'm new to php / mysql. I'm trying to change an existing script to take the results and then insert the value into the database.
This is what I've tried. I'm guessing I'm missing something or the syntax is wrong:
// unique reference number is generated.
// check if it exists or not
$query = "SELECT `ID_UNIQUE` FROM `tbl_referrals`
WHERE `ID_UNIQUE`='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
// We've found a unique number. Lets set the $unique_ref_found
// variable to true and exit the while loop
$unique_ref_found = true;
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
(`ID_UNIQUE`)";
}
}
echo 'Your reference number is: '.$unique_ref;
Ticks are for identifiers, single quotes are for string values:
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
('ID_UNIQUE')";
}
Related
I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.
I am trying to read a file of data and insert into a table in mySQL. I have tried building an array and imploding, as well as a foreach loop like this one but only get back the first row of the table.
<?php
$str = file_get_contents('-');
$con = mysqli_connect('-', '-', '-','-');
$dataArray = explode("|",$str);
$blahArray = array();
foreach($dataArray as $info){
$pD = unserialize($info);
$pD->*->*->*;
$pL = $pD->*->*->*[0];
$blah = $pL->BLAH;
array_push($blahArray,$blah);
}
foreach($blahArray as $val){
$sql = "INSERT INTO table (BLAH)
VALUES('$val')";
mysqli_query($con,$sql);
}
?>
I have a lot more datafields to enter but for debugging am just trying the one. Any help or suggestions would be greatly appreciated!
I can't say for certain what is wrong with your code, but here is a modification you can make which might tell you what is going on:
foreach($apnArray as $val) {
$sql = "INSERT INTO property (APN) VALUES('$val')";
$result = mysqli_query($con, $sql);
if (false===$result) {
printf("error: %s\n", mysqli_error($con));
}
}
Check for two things. First, make sure that you are in fact looping 90 times. Second, see if each INSERT query be executing with or without error.
Update:
Based on your comment, it appears that you have a primary key with a unique constraint, which is not set to autoincrement. In your INSERT query, you are only setting a value for the APN column and nothing else. This means that MySQL is using a default value (0) for this primary key. The solution to your problem is to pass in a unique value for the primary key or to set that primary key column to autoincrement.
Try this:
$sql = "INSERT INTO property (APN)
VALUES";
foreach ($apnArray as $val) {
$sql .= "('$val'),";
}
$sql = trim($sql, ",");
mysqli_query($con, $sql);
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!
Hi guys am fighting with a syntax error of my sql, saying exactly:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax"
Even though the code is working and doing what I wanted I still get the syntax error info!
and here is the code:
$person_id =mysql_query("SELECT person_id FROM person WHERE firstname='$array[0]' AND lastname='$array[1]' AND city='$array[2]' ")
or die(mysql_error());
if (mysql_num_rows($person_id) )
{
print 'user is already in table';
}
else
{
mysql_query ("INSERT INTO person VALUES (NULL, '$array[0]' ,'$array[1]' , '$array[2]' ")
or die(mysql_error());
$person_id = mysql_insert_id();
}
$address_id =mysql_query("SELECT address_id FROM address WHERE street='$array[3]' AND city='$array[4]' AND region='$array[5]'")
or die(mysql_error());
if (mysql_num_rows($address_id) )
{
print ' already in table';
}
else
{
mysql_query ("INSERT INTO address VALUES (NULL, '$array[3]', '$array[4]', '$array[5]'")
or die(mysql_error());
$address_id = mysql_insert_id();
}
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)")
or die(mysql_error());
Thanks for any suggestions
It's probably because you haven't escaped your values...
Try:
$query = "SELECT age FROM person WHERE name='".mysql_real_escape_string($array[0])."' AND lastname='".mysql_real_escape_string($array[1])."' AND city='".mysql_real_escape_string($array[2])."'";
And read up on SQL injection.
EDIT
I think your problem is that you are trying to pass mysql result resources directly into a string, without fetching the actual values first.
Try this:
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the person already exists in the database, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]')";
mysql_query($query) or die(mysql_error());
$person_id = mysql_insert_id();
}
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// INSERT a record linking person and address
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)") or die(mysql_error());
ANOTHER EDIT
Firstly, I have modified the code above - added a couple of comments, corrected a couple of small errors where the wrong variable was referenced and re-spaced it to make it more readable.
Secondly...
You are getting that additional error because you are trying to insert a new row into your person_address table, which doesn't seem to have a sensibly configured primary key. The easy work around to the problem you currently have is to run a SELECT against this table to see if you have already got a record for that user, then if you have you can do an UPDATE instead of the INSERT to alter the existing record.
However, if I understand what your doing here correctly, you don't actually need the person_address table, you just need to add another integer column to the person table to hold the ID of the corresponding row in the address table. Doing this would make many of your future queries potentially much simpler and more efficient as it will be much easier to SELECT data from both tables at once (you could do it with your current structure but it would be much more confusing and inefficient).
The following code example could be used if you add another integer column on the end of your person, and call that column address_id. You will notice it's very similar to the above, but there are two key differences:
We do the address stuff first, since we will keep track of the relation in the person record
We do an UPDATE only if we find a person, otherwise we just INSERT a new person as before
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// See if the person already exists in the database, UPDATE if he does, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
$query = "UPDATE person SET address_id = '$address_id' WHERE person_id = '$person_id'";
mysql_query($query) or die(mysql_error());
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]', '$address_id')";
mysql_query($query) or die(mysql_error());
}
If we structure the database in this way, it allows us to do this:
SELECT person.*, address.* FROM person, address WHERE person.address_id = address.address_id AND [some other set of conditions]
Which will return the person record, and the address record, in the same result set, all nicely matched up for you by the database.
YET ANOTHER EDIT
You need to add an auto-increment primary key to the person_address table, and perform a SELECT on it to make sure you are not adding duplicate records.
You should replace the final INSERT statement with the following code segment. This code assumes that you have a primary key in the person_address table called relation_id. It also assumes that the id field names in this table are named in the same way as they are in the other two tables.
// See if a relation record already exists for this user
// If it does, UPDATE it if the address is different
// If it doesn't, INSERT an new relation record
$query = "SELECT relation_id, address_id FROM person_address WHERE person_id = '$person_id' LIMIT 1";
$relation = mysql_query($query);
if ( mysql_num_rows($relation) ) {
$relation = mysql_fetch_assoc($relation);
if ($relation['address_id'] == $address_id) {
print 'The record is identical to an existing record and was not changed';
} else {
$relation_id = $relation['relation_id'];
$query = "UPDATE person_address SET address_id = '$address_id' WHERE relation_id = '$relation_id'";
mysql_query($query) or die(mysql_error());
}
} else {
$query = "INSERT INTO person_address VALUES(NULL, '$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
EVEN MORE EDITING
Try this to replace the code from above:
// See if a relation record already exists for this user
// If it doesn't, INSERT an new relation record
$query = "SELECT person_id FROM person_address WHERE person_id = '$person_id' AND address_id = '$address_id' LIMIT 1";
$relation = mysql_query($query);
if ( !mysql_num_rows($relation) ) {
$query = "INSERT INTO person_address VALUES('$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
You cannot use array values like that inside of quotes - instead you could, for example, separate the values from the query using dots.
$query = "SELECT age FROM person WHERE name='".$array[0]."' AND lastname='".$array[1]."' AND city='".$array[2]."'";
the second and fourth query do not have an ending ')' at the end of the values