Php counter and Substring Concatenation - php

I am working on a car rental system, where the user can add a car into the php script which thereby adds the values into the back end dababase. I have a field called 'ID' which is auto incremented INT field. Everytime I add a car, the value is automatically added as an incremented Integer. Now, how I actually want it to be is different, for example if the name of the car to be added is 'MERCEDES', the ID value should be MER001. If the next car then added is VAUXHALL, the ID value should be VAU002 and so on. I know how to get 'MER' out of mercedes using the substring function in php, but I dont know how to have a loop counter and concatenate it with the extracted substring. I believe for this the ID field in my database table will have to be a VARCHAR but I dont know if a VARCHAR can be auto-incrementing (doesnt make sense). Here's the form to add the car.
Add a new Car to the database
Fill in the details below to Register
<label> Car Name
<span class="small">Enter car name</span>
</label>
<input type="text" name="CARNAME" id="CARNAME" />
<label>Fuel Type
<span class="small">Eg: Petrol</span>
</label>
<input type="text" name="FUELTYPE" id="FUELTYPE" />
<label>Transmission
<span class="small">Eg: Manuel</span>
</label>
<input type="text" name="TRANSMISSION" id="TRANSMISSION" />
<label>Engine Size
<span class="small">Eg: 2.4</span>
</label>
<input type="text" name="ENGINE_SIZE" id="ENGINE_SIZE" />
<label>Doors
<span class="small">Eg: 4</span>
</label>
<input type="text" name="DOORS" id="DOORS" />
<label>Total
<span class="small">Eg: 40</span>
</label>
<input type="text" name="TOTAL" id="TOTAL" />
<label>Available
<span class="small">Eg: 40</span>
</label>
<input type="text" name="AVAILABLE" id="AVAILABLE" />
<input type="submit" name="submit" value="Add Car">
<div class="spacer"></div>
</form>
This form takes you to adding.php which has the following code:
<?php
$link = mysql_connect ("xxxxx", "xxxxx", "xxxxx");
mysql_select_db ("xxxxx");
$ID = $_POST['ID'];
$CARNAME = $_POST['CARNAME'];
$FUELTYPE = $_POST['FUELTYPE'];
$TRANSMISSION = $_POST['TRANSMISSION'];
$ENGINE_SIZE = $_POST['ENGINE_SIZE'];
$DOORS = $_POST['DOORS'];
$TOTAL = $_POST['TOTAL'];
$AVAILABLE = $_POST['AVAILABLE'];
$DATEADDED = $_POST['DATEADDED'];
$test = substr($CARNAME,0,3); //tried to use this test variable and it works to get the substring!
if($TOTAL>=$AVAILABLE)
{
$query = "insert into car (ID,CARNAME,FUELTYPE,TRANSMISSION,ENGINE_SIZE,DOORS,TOTAL,AVAILABLE,DATEADDED) values ('$_POST[ID]','$_POST[CARNAME]','$_POST[FUELTYPE]','$_POST[TRANSMISSION]','$_POST[ENGINE_SIZE]','$_POST[DOORS]','$_POST[TOTAL]','$_POST[AVAILABLE]',CURDATE())";
$result = mysql_query($query);
header("location: list_logged.php");
}
else
{
echo "<script>alert('The Total number of cars cannot be less than Available number!'); location.href='add.php';</script>";
}
mysql_close ($link);
?>
Any suggestions as to how I can post something to ID to make it like MER001, MAC002...and so on? Right now it is just set to an auto incrementing value, which is added automatically. I know I'd have to change the field in the database from ID to VARCHAR but I dont know what to do next. I tried searching similar questions on substr and php counter concatenation but found nothing useful.

Spent some time and figured it out. You should really use PDO though. Also your database will look like this:
ID, CARNAME, FUELTYPE, TRANSMISSION, ENGINE_SIZE, DOORS, TOTAL, AVAILABLE, AND DATEADDED (WHICH IS A DATETIME DATA TYPE. THE REST ARE ALL VARCHARS).
One more thing. Instead of using CURDATE() you use NOW() which gives the date and time of insert into the db.
<?php
$link = mysql_connect ("***", "****", "*******");
mysql_select_db ("*****");
$CARNAME = $_POST['CARNAME'];
$FUELTYPE = $_POST['FUELTYPE'];
$TRANSMISSION = $_POST['TRANSMISSION'];
$ENGINE_SIZE = $_POST['ENGINE_SIZE'];
$DOORS = $_POST['DOORS'];
$TOTAL = $_POST['TOTAL'];
$AVAILABLE = $_POST['AVAILABLE'];
//FUNCTION TO GET LAST ID FROM DB
function getLastID(){ //Function to get last ID created and return
$query = "SELECT ID FROM car ORDER BY DATEADDED DESC LIMIT 1;";
$lastID = mysql_query($query);
$results = mysql_fetch_assoc($lastID);
return $results; //returns last id
}
//SWITCH CASE TO CREATE PREPENDING CARNAME
switch ($CARNAME) { //PreString based off of form input
case 'MERCEDES':
$preString = 'MER';
break;
case 'VAUXHALL':
$preString = 'VAU';
break;
default:
$preString = 'NONE';
break;
}
//CREATING NEW INDEX
$newID = getLastID(); // Get Newest ID from the database
$castNewID = (String) $newID['ID']; //Cast ID to String
$last3chars = substr($castNewID, -3); //Get last three characters of ID
$newIndexNumber = (int) $last3chars + 1; // Cast last3chars to int and add one
$castToString = str_pad((String) $newIndexNumber, 3, "0", STR_PAD_LEFT); //Append zeros to string if we haven't reached 100 yet and cast back into a string.
$newCarID = (String) $preString . (String) $castToString; //Finally create new ID concatenation
//var_dump($newCarID); //For debugging
//INSERT INTO DB
if($TOTAL>=$AVAILABLE)
{
$query = "insert into car (ID,CARNAME,FUELTYPE,TRANSMISSION,ENGINE_SIZE,DOORS,TOTAL,AVAILABLE,DATEADDED)
values ('$newCarID', '$CARNAME', '$FUELTYPE','$TRANSMISSION','$ENGINE_SIZE','$DOORS','$TOTAL','$AVAILABLE',NOW())";
$result = mysql_query($query);
header("location: list_logged.php");
}
else
{
echo "<script>alert('The Total number of cars cannot be less than Available number!'); location.href='add.php';</script>";
}
mysql_close ($link);
?>

Related

php POST form query update dinamic variables [duplicate]

i have this form
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and we make this query on process.php
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."'
WHERE
`id` = '".$id."'";
and if i edit the table languages and add more languages the form dynamically will modify to lets say this example
<form method="post" action="process.php">
Name: <input type="text" name="name" value="">
<br />
English: <input type="text" name="english" value="">
<br />
French: <input type="text" name="french" value="">
<br />
Spanish: <input type="text" name="spanish" value="">
<br />
German: <input type="text" name="german" value="">
<br />
<input type="submit" name="submit" value="Submit">
</form>
and the query i need to dynamically be edited
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."'
WHERE
`id` = '".$id."'";
what i don't understand is how i make this dynamically inside the query the code
*the name of the form field is the same of the name of the variable i POST
*and the name of the column from the table is the same of the name of the POST
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."',
`german` = '".utf8_encode($german)."',
`other_language` = '".utf8_encode($other_language)."',
`other_language2` = '".utf8_encode($other_language2)."'
here above i have explained how i make the query but i cant understand how to write the variables
I know is a little bit difficult what i need but maybe someone understand what i need
thank you
Above this line is the edited message because someone flagged this message answered
I will explain first what i want to do:
I have a table called "translations" where i store the languages. ex: english, french, spanish, etc.
I use a form to update the new values, the problem is that i want to do it dynamically not to insert this query on every php file manually because the languages table will grow or edit and i want to work dynamically not to edit every php file.
the variable names are the same like fields name in database
i manage to make an array for the names on table translations
this is what i have until now to make it dynamic
the problem is i don't know how to insert variables in the query $_POST['english'], $_POST['french'], etc
$db = new DB();
$query = $db->query("SELECT * FROM `translations_languages` ORDER BY `name` ASC");
while($row = $query->fetch_assoc()){
$values[] = "`{$row['name']}` = '{$row['name']}'";
}
$dynamic_result = "".strtolower(implode(",", $values))."";
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
$dynamic_result
WHERE
`id` = '".$id."'
";
echo "$query";
and this is how the query looks normally
$query = "
UPDATE
`translations_structure`
SET
`updated_on` = '".time()."',
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
WHERE
`id` = '".$id."'";
i want to add these values to the query
`english` = '".utf8_encode($english)."',
`french` = '".utf8_encode($french)."',
`spanish` = '".utf8_encode($spanish)."'
you just need to create a dynamic update array. Something like this:
$languagesToUpdate = array();
// this is an example, you should modify as your script:
// create a variable/constant to make sure you update only allowed fields
$allowedLanguages = array('english' => true, 'french' => true, 'spanish' => true, 'german' => true, 'other_language' => true);
// iterate threw post and check for allowed languages and add to languagesToUpdate the language we need to update with it's value
foreach ($_POST as $post => $value) {
if (isset($allowedLanguages[$post]) && $allowedLanguages[$post]) {
$languagesToUpdate[] = '`' . $post . '` = "' . utf8_encode($value) . '"';
}
}
// add additional data like updated_on
$languagesToUpdate[] = '`updated_on` = ' . time() . '';
//update database
$db = 'UPDATE `translations_structure` SET '.implode(', ', $languagesToUpdate).' WHERE `id` = '.(int)$id;
// this will produce something like this:
// UPDATE `translations_structure` SET `english` = "English text", `spanish` = "Spanish text", `updated_on` = 1479720637 WHERE `id` = 1

put tick on checkbox based on database value

I'm updating some countries values into db table. All countries fetch from TBL_COUNTRY table. Then few countries store to another table. I'm using implode function to store multiple values. it works fine. it stored like this in my db table Afghanistan,Argentina,Austria,Bangladesh.
I have tried this code
<?php
$exp_str = explode(',', $model_availability);
foreach($exp_str as $get_str)
{
echo $get_str;
}
?>
This above code return this output AfghanistanArgentinaAustriaBangladesh
How do I put tick on the checkbox based on this value?
<?php
$sql = "SELECT * FROM ".TBL_COUNTRY." ORDER BY country_name ASC";
$exe = mysql_query($sql, $CN);
while($r = mysql_fetch_array($exe))
{
?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>" />
<label for="<?=$r['country_name']?>"><?=$r['country_name']?></label>
<?php } ?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>"<?=(in_array($r['country_name'],$model_availability)?" checked":"")?> />
//In the input box just add a checked attribute, you will get.
" id="" checked = "true" />

loop to update data coming from form php mysql html

I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays.
the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you
//update data
$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];
$i = -1;
foreach($priority as $priori)
{
++$i;
$row_enable = $enable[$i];
$row_height = $height[$i];
$row_prio = $priority[$i];
$positio = $position[$i];
$disp = $display[$i];
$widgeti = $widgetid[$i];
if (isset($enable[$i]))
$enables ="y";
else
$enables ="n";
if (isset($display[$i]))
$displ = "y";
else
$displ = "n";
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
$updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";
echo $updater."<br>";
} // ends here
There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
...
You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:
<input type="text" name="data[w1][position]">
<input type="text" name="data[w1][height]"> ...
...
<input type="text" name="data[w2][position]">
<input type="text" name="data[w2][height]"> ...
...
Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:
foreach($_POST['data'] as $widgetid => $data) {
// Make sure to check if the values won't make your SQL query vulnerable to injection!
// http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
$widgetid = mysql_real_escape_string($widgetid);
$position = is_numeric($data['position']) ? $data['position'] : 0;
// ...
// Build your update query here
}

Update query PHP MySQL [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
PHP UPDATE prepared statement
(3 answers)
Closed 11 months ago.
Can anybody help me understand why this update query isn't updating the fields in my database? I have this in my php page to retrieve the current values from the database:
<?php
$query = mysql_query ("SELECT * FROM blogEntry WHERE username = 'bobjones' ORDER BY id DESC");
while ($row = mysql_fetch_array ($query))
{
$id = $row['id'];
$username = $row['username'];
$title = $row['title'];
$date = $row['date'];
$category = $row['category'];
$content = $row['content'];
?>
Here i my HTML Form:
<form method="post" action="editblogscript.php">
ID: <input type="text" name="id" value="<?php echo $id; ?>" /><br />
Username: <input type="text" name="username" value="<?php echo $_SESSION['username']; ?>" /><br />
Title: <input type="text" name="udtitle" value="<?php echo $title; ?>"/><br />
Date: <input type="text" name="date" value="<?php echo $date; ?>"/><br />
Message: <textarea name = "udcontent" cols="45" rows="5"><?php echo $content; ?></textarea><br />
<input type= "submit" name = "edit" value="Edit!">
</form>
and here is my 'editblogscript':
<?php
mysql_connect ("localhost", "root", "");
mysql_select_db("blogass");
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$udtitle = $_POST['udtitle'];
$udcontent = $_POST['udcontent'];
mysql_query("UPDATE blogEntry SET content = $udcontent, title = $udtitle WHERE id = $id");
}
header( 'Location: index.php' ) ;
?>
I don't understand why it doesn't work.
You have to have single quotes around any VARCHAR content in your queries. So your update query should be:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
Here i updated two variables and present date and time
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns,
Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

PHP and MySQL form, what am I doing wrong?

I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>
1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());
Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.
At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)

Categories