okay as the title says I have a lot of tables and I need to display them in different drop down boxes. I have so far got the first table to display inside of a drop down box but I'm not really sure how too get the next table display.
<?php
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$selected = mysql_select_db("database",$link)
or die("Could not select examples");
$sql="SELECT * FROM MOBO CPU, RAM,GPU, PSU, COMPUTERCASE";
$result = mysql_query($sql);
echo "<select name='mobo'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'">'.$row["mobo"].'</option>';
}
echo "</select>";
?>
so this is my php so far and this is how the database looks.
CREATE TABLE MOBO (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,mobo VARCHAR(50) UNIQUE,quantity INT,price DECIMAL(18,2));
CREATE TABLE CPU (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, cpu VARCHAR(50) UNIQUE, quantity INT, price DECIMAL(18,2));
CREATE TABLE RAM (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,ram VARCHAR(50) UNIQUE,quantity INT,price DECIMAL(18,2));
and so on also I was hoping for somebody if they manager to fix my problem to explain in detail of how its done I'm a PHP Newb.
First of all, you're using mysql_* functions and they are removed in the latest version of PHP. While it works now, you will have an issue upgrading to a later version of PHP in the future. Use Mysqli or PDO (PDO is my preference)
Secondly, use lower case in identifiers such as your table names. This code might work on Windows, but if you ever migrate to Linux all of this will be case sensitive and this code will fail to work.
And what I do not understand in this code, while ($row = mysql_fetch_array($result)) {. mysql_fetch_array() returns the complete set of the result from the database. A while loop will constantly redefine it's value and you should instead use foreach($var = mysql_fetch_array(...) as $key => $value){} and then still it would be better to define $var in my example separately before using it in a foreach loop.
Then I think your issues are resolved.
$sql="SELECT * FROM mobo, cpu, ram, gpu, psu, case";
if($result = mysql_query($sql) != false){ // you should actually check if the query ran successfully.
$data = mysql_fetch_array($result);
//echo "<select name='mobo'>";
foreach($data as $row => $value){
echo $row, $value, "</br>";
}
//echo "</select>";
}
And last of all, selecting everything from multiple tables is a bad database setup. It will drag you down once you have a lot of results in the database and then it will be an issue to resolve this. Its perhaps better to use inner or outer joins by id.
Related
I've just noticed that my rand values are being saved in ascending order (lower to higher), but I'm not telling it to save it in ascending order. However when I echo the rand, it shows the value in normal way.
Source code:
<?php
try {
$db = new PDO('sqlite:randvalue.sqlite');
$db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");
$i=1;
while($i <= 12) {
$randNum = rand(1,100);
$finalval = $randNum;
$stmt = $db->prepare('INSERT INTO company (revenue_value) VALUES (?)');
$stmt->execute(array("$finalval"));
echo "$finalval";
echo "<br>";
$i++;
};
print "<table border=1>";
print "<tr><td>value</td>";
$result = $db->query('SELECT * FROM company');
foreach($result as $row) {
print "<tr><td>".$row['revenue_value']."</td>";
}
print "</table>";
$db = NULL;
} catch(PDOException $e) {
print 'Exception : '.$e->getMessage();
}
?>
Result:
How do I make it not to save the value in table in non-ascending order just like in echo where the values are not in ascending order?
The database will attempt to store the rows in the most efficient way it can for fast lookup. This means storing them in the order defined by the primary key of the table, if one exists, and in this case, the revenue_value column is the primary key. There's no guarantee that the order in which records are inserted is the order in which they will come back when you do a SELECT.
If you want to pull the back in the records same order, you'll need a separate column to store the order in which they are inserted. Typically, you'd use a AUTO_INCREMENT column that's also the primary key of the table. Add a column like this and you'll be able to pull them back in the order in which they are inserted by using an ORDER BY clause. However, as I said, the database will usually attempt to store the rows efficiently, it order them by the primary key column anyway, so typically you wouldn't need the ORDER BY, but it's still a good idea to include one in any query where the order of the results is important.
thanks to #Rizier manage to find the problem
just remove the primary key
$db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");
to
$db->exec("CREATE TABLE company (revenue_value INTEGER, month VARCHAR)");
I have the below code, which works perfect. What i want to do is to check the refNo first to see if there are duplicates entries in MySQL. If there is then appear a warning message, otherwise appear a "ok" message. How can i do that with PDO? Any help?
(include("db.php"));
$SQLquery = "INSERT INTO mydatabase (refNo, name)
VALUES ('".$_POST["refNo"]."', '".$_POST["name"]."');";
$STH = $dbc->query($SQLquery);
?>
edit: Hello guys,
i prefer not to add primary keys. Is there any other way?
Set up refNo as a primary key. You could also create it as unique but that defeats the purpose - your reference number appears to be a unique primary identifier. Perfect choice for a primary key.
Further, change your query
try {
$SQLquery = "INSERT INTO mydatabase (refNo, name) VALUES (:refNo, :name)";
$SQLquery = $dbc->prepare($SQLquery);
$SQLquery->bindValue(':refNo', $_POST['refNo']);
$SQLquery->bindValue(':name', $_POST['name']);
$SQLquery->execute();
} catch (Exception $e) {
die("Insert error");
}
$count = $SQLquery->rowCount();
if ($count == 1) {
echo "Record added!";
}
This binds the post value to prevent SQL injection too.
Edit: You could follow this up with $count = $SQLquery->rowCount(); which will be 1 if the insert was successful, as it appears you've edited your question since you posted it for more info.
If you want to do this without using a database level constraint, you'll need to do an extra SELECT statement before inserting into the table. But that gives you no absolute guarantees, as it might be two processes want to insert the same row at the same time and they will still succeed.
-- it'll look a little something like this; I'm not familiar with PDO but the structure should be the same
$selectQuery = "SELECT * FROM mydatabase
WHERE refno = '".$_POST["refNo"]."'";
$res = $dbc->query( $selectQuery );
if( $res->count() > 0 ) {
// this result already exists; show error
}
else {
// this result is new; put the insert query here
}
I have a table with a lot of columns. I have a function that duplicates my record into a new row with an updated auto-incremented ID.
The function works perfectly however, on some of my INT columns, sometimes I have a NULL as the default. When the record is duplicated, it turns my NULL placement into a 0.
I'm assuming it's because I am doing '" . value . "'
Could anyone help me figure out how I could make NULL values be inserted as " . NULL . " and keep my other values as '" . value . "'?
EDIT I'm having trouble differentiating a null and a blank value. I've tried empty() and is_null() and a varchar with no value and an INT with a NULL value isn't showing a difference
note: I understand that I am using an outdated mysql extension. For right now, I'm just trying to process my null variables correctly.
function duplicateRow($table, $id_field, $id_value)
{
// copy content of the record you wish to clone
$entity = mysql_fetch_array(mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id_value}"), MYSQL_ASSOC) or die("Could not select original record");
// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id
$entity[$id_field] = "";
// insert cloned copy of the original record
mysql_query("INSERT INTO {$table} (".implode(", ",array_keys($entity)).") VALUES ('".implode("', '",array_values($entity))."')") or die(mysql_error());
//returns the new id
return mysql_insert_id();
}
You don't need to fetch the data into PHP only then to send it back to MySQL: INSERT ... SELECT is a single SQL command that enables the whole shebang to take place natively within the database.
However, you need to exclude the $id_field from the operation, so you can't use the * wildcard but must instead explicitly list the column names. This adds some complexity, especially to perform the operation in a safe, injection-proof way:
function duplicateRow($table, $id_field, $id_value)
{
// prevent SQL injection
$enc_map = array(
'utf8' => 'UTF-8',
'latin1' => 'Windows-1252' // etc.
);
mb_regex_encoding($enc_map[mysql_client_encoding()]);
$table_safe = '`'.mb_ereg_replace('`', '``', $table ).'`';
$id_field_safe = '`'.mb_ereg_replace('`', '``', $id_field).'`';
$id_value_safe = mysql_real_escape_string($id_value);
// fetch column names
$fields = array();
$qry = mysql_query("SHOW COLUMNS FROM $table_safe");
while ($row = mysql_fetch_assoc($qry))
if ($row['field'] != $id_field)
$fields[] = '`'.mb_ereg_replace('`', '``', $row['field']).'`';
$fields_safe = implode(',', $fields);
// duplicate the record
mysql_query("
INSERT INTO $table_safe
($fields_safe)
SELECT $fields_safe
FROM $table_safe
WHERE $id_field_safe = '$id_value_safe'
");
//returns the new id
return mysql_insert_id();
}
Note that the ancient ext/mysql extension has been deprecated and its use in new code has been discouraged for years. You should seriously consider switching to either MySQLi or PDO.
What is your MySQL Version? some versions of MySQL (5.5 and earlier if I'm not mistaken) convert null values to empty for string fields and 0 to int fields.
You have to force null value or update to MySQL 5.6
I ended up making a foreach statement that checked to see if my value was null and changed the query a little bit. This may not be the greatest, the right, or practical way to do this but it works. If anyone has any suggestions, they are 100% appreciated!
The reason I kept my function mostly the same is I needed to use this for multiple large tables. So I didn't know exactly what the fields were going to be.
function duplicateRow($table, $id_field, $id_value)
{
// copy content of the record you wish to clone
$entity = mysql_fetch_array(mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id_value} AND snapshot=0"), MYSQL_ASSOC) or die("Could not select original record");
foreach ($entity as &$value) { if(is_null($value) == true) { $value = "NULL"; } else { $value = "'$value'"; } }
// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id
$entity[$id_field] = "'";
// insert cloned copy of the original record
$query = "INSERT INTO {$table} (".implode(", ",array_keys($entity)).") VALUES ('".implode(", ",array_values($entity)).")";
mysql_query($query) or die(mysql_error());
//returns the new id
return mysql_insert_id();
}
My objective
To add a number of columns to a MySQL table. I have two concerns:
1) How to do this
2) Is this a bad idea, and if so why?
My reason for wanting to do this:
I have a form with a systematically named set of fields (e.g. field_1 field_2 etc). I want to post that data to a page and have it store it the mysql table, and I would like the fields to enter columns of a corresponding name (i.e. columns are named field_1 field_2 etc)
Rather than manually creating a column for each field name manually, it seemed obvious to loop the task.
However, research here and here seems tells me this approach illicits horror from people, and I found no actual solutions.
My attempt:
$mysqli = new mysqli("localhost","user","password","db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$i = 1;
while ($i <= 14)
{
$column = 'field_'.$i;
$sql= '"ALTER TABLE supply ADD '.$column.' VARCHAR(45)"';
$mysqli->query($sql);
printf("Affected rows (ALTER): %d\n", $mysqli->affected_rows);
$i++;
}
This seems to run without error, however the affected rows message gives me (per loop, so 14 of these):
Affected rows (ALTER): -1
and the columns are not being added.
Can anyone advise me of my error, or a better way to debug what is going wrong? Additionally if this is an unwise thing to be doing could could you explain why and what I should consider doing instead? Thank you.
Thats because affected_rows are set when you use only statements:
INSERT
UPDATE
REPLACE
DELETE
which work with rows, with data inside your table.
When you use ALTER your result should be true or false, because you do not work with data, you just edit the structure of your table.
$result = $mysqli->query($sql) ;
if ($result){
echo "Table is updated. New column {$column} added" ;
}
Also, the correct SQL here would be:
$sql = "ALTER TABLE supply ADD {$column} VARCHAR(45) ; " ;
I have the following PHP code that allows me to read in from a text file line by line and write to a MySQL database. The text file consists of 13 values seperated by a space on each line. I have created the table separately in SQL, (with all the relevant Fields needed: Time, WIMU_ID, Ax, Ay etc) and then run the PHP below to INSERT the values into the table. My question is: Is there any way to create the table within the PHP code below and not have to CREATE the table in SQL first? Any help or suggestions appreciated.
Hugh.
<?php
$connection = mysql_connect('localhost','root','bonzo123');
mysql_query('create database gameDB');
mysql_select_db('gameDB');
$wx = array_map('trim',file("Thu-Apr-01-09_41_01-2010.txt_calibrated_120Hz.txt"));
$newwx = array();
foreach($wx as $i => $line)
{
if ($i > 1)
{
$tmp = array_filter(explode(' ',$line));
$q = "insert into test1 (Time, WIMU_ID, Ax, Ay, Az, Gx, Gy, Gz, Mx, My, Mz, Ax70, Ay37) values ('" . implode("','",$tmp) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
?>
I think what you really want is this:
http://dev.mysql.com/doc/refman/5.1/en/load-data.html
which you can invoke through PHP but this would be a lot better unless you have specific reasons it cannot be used.
Sure, you can execute a command like:
CREATE TABLE IF NOT EXISTS `test1` (
...
);
To get your table creation query, issue this command after you've already created it in SQL:
SHOW CREATE TABLE `test1`;
Edit:
Note that you don't have to create the table in SQL directly, but since you already have, issuing the above command will give you exactly what you need to include in PHP to have it create the table on a future installation should the table not exist.
Note also that as #Jeremy suggests, you don't have to "roll your own" code to import a data file to a table. Once you've created the table, you can use LOAD DATA INFILE... to populate the table.
Edit 2:
Here is an example based on your comment:
<?php
// Connect to the database server
$connection = mysql_connect('localhost', 'root', 'bonzo123');
if (!$connection)
die('Could not connect: ' . mysql_error());
// Create database gameDB
if (mysql_query('create database gameDB', $connection)) {
echo "Database gameDB created successfully.\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n:";
}
// select which database to use
mysql_select_db('gameDB', $connection);
// create table test1 if it doesn't already exist
mysql_query('CREATE TABLE IF NOT EXISTS test1 (
v1 varchar(100),
v2 varchar(100),
v3 varchar(100),
v4 varchar(100),
v5 varchar(100),
v6 varchar(100),
v7 varchar(100),
v8 varchar(100),
v9 varchar(100),
v10 varchar(100)', $connection);
?>