I am working with a php program and want to check if a table exists. If it does exist, do nothing, if it doesn't create and populate the table. I ran across
if(mysql_query("DESCRIBE `table`")) {
// Exists
}
but this only takes action if it does exist. Would this
if(!mysql_query("DESCRIBE `table`")) {
// create and populate table
}
do what I am asking?
What you're doing won't work because the test is only testing the return value of the mysql_query() call, not the result of the query itself.
You need to query the tables with SHOW TABLES LIKE 'table' and check the number of rows returned:
$db = new mysqli(...);
$result = $db->query("SHOW TABLES LIKE 'table'");
if ($result->num_rows == 0) {
// create table
}
Note: mysql_*() is deprecated - you shouldn't use it for new code.
You'll find the MySQL reference here, and the PHP reference for mysqli here
Related
With php ibase, ibase_query fetches the relation, several functions can then fetch rows from that relation, but all these functions extract the next row.
In Delphi I have the ability to return to the first row (DataSet.First;) - is there any equivalent in PHP ibase?
I could of course re-query the database, but this seems a waste of resources if the original relation is still accessible.
Example code:
$table = ibase_query($sql);
$row = ibase_fetch_object($table);
while (!empty($row))
{
echo $row->ENTRYNO.'<br>';
$row = ibase_fetch_object($table);
}
//The missing functionality
$table.First;
//or maybe
$row = ibase_fetch_object($table,first);
//in which case of course the following line would be redundant
$row = ibase_fetch_object($table);
while (!empty($row))
{
//process record
$row = ibase_fetch_object($table);
}
The ibase/firebird-php driver is only able to fetch forward. If you want to consult earlier rows, you will need to store them yourself in some form, or execute the query again.
How can I list names of tables in sql database and the table columns for the each table and then get a json encoding of the results in PHP?
Here is code to display tables:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) {
// go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
You could create an array/object and add the data to it. To get a json result just call json_encode on the array/object.
Here is what I would do:
// Create an object
$results = new stdClass();
// Get all tables
$result = mysql_query("show tables");
// Always check if the query returned anything to prevent possible errors
if(mysql_affected_rows() > 0) {
// Loop through each table
while($table = mysql_fetch_assoc($result)) {
// Get the columns in the table
$resultColumns = mysql_query("show columns from ".$table);
if(mysql_affected_rows() > 0) {
// Columns found. Create a new property in the object and assign the columns to it
$tableColumns = mysql_fetch_assoc($resultColumns);
$results[$table] = $tableColumns;
}
else {
// No columns found. Create a new property in the object and assign a blank array.
$results[$table] = [];
}
}
}
Now we can return that data as a json with json_encode($results).
http://php.net/manual/en/function.json-encode.php
As a side note, I would look to use mysqli, not mysql (as it is now depreciated). The syntax for it is basically exactly the same, but you need to pass the connection variable as the first parameter in most cases. So it would be useful to use create a database/connection class and call to those methods, instead of calling mysql or mysqli functions directly.
See here: https://www.w3schools.com/php/php_ref_mysqli.asp
And here (an example): https://www.johnmorrisonline.com/simple-php-class-prepared-statements-mysqli/
Note: This is pseudo code and not tested but should be okay. Let me know if you need any help with it.
I created a function that tries to UPDATE a value using a condition. If something goes wrong, it tries to do a INSERT.
The code is as follow:
if(!$result=$this->query("UPDATE collect_data_settings SET setting_value ='".$setting_value."' WHERE collect_point = '".$collect_point."' AND setting_name='".$setting_name."';"))
$result=$this->query("INSERT INTO collect_data_settings ('collect_point','setting_name','setting_value') VALUES ('".$collect_point."','".$setting_name."','".$setting_value."');");
Unfortunately, for some reason the UPDATE query never returns false even if the condition is not satisfied. Can someone help me?
Why don't you try doing a search for the collect_point (assuming this is a unique key) variable first and if it is not yet in the database you use the INSERT statement and if not you use the UPDATE statement. For example:
$db = new SQLite3('database.db')
$check = $db->query("SELECT * FROM collect_data_settings WHERE collect_point = '$collect_point'")
$check_query = $check->numRows();
if($check_query > 0) {
*Your UPDATE query*
}else {
*Your INSERT query*
}
The UPDATE statement modifies all rows that happen to match the WHERE condition. The final number does not matter; even if no row matches, all rows were checked successfully.
To find out how many rows were changed, use the changes() function:
$this->exec("UPDATE ... WHERE ...");
if ($this->changes() == 0)
$this->exec("INSERT ...");
Lets say I have a database full of info, and I want the user to find his info by inputting his ID. I collect the input of the user with:
'$_POST[PID]'
And want to put it into a resource variable like:
resource $result = '$_POST[PID]';
In order to print out their information like :
while($row = mysql_fetch_array($result))
{
echo all their information
echo "<br>";
}
However I cannot create the resource variable because it is telling me that it is a boolean. How can I fetch that resource in order to print the list?
Several problems with this
First, a resource is something like a database result set, a connection (like fsockopen), etc. You can't just declare or typecast a variable into a result set
Second, you need to do something like SQL to fetch the data based on that ID. That involves connecting to the DB, running your query and then doing your fetch_array
Third, mysql_ functions are depreciated. Consider using mysqli instead.
I think you're having problems displaying the result set.
Try this
$id = $_POST['PID'];
$result = "SELECT * FROM table WHERE id ='.$id.'";
while($row = mysqli_query($result))
{
echo $row[0]; //or whichever column you want to display.
//$row[0] will display your
// PK
}
I am trying to implement a function that will insert a new entry in a database if a field with same name (as the one given) doesn't already exist. In particular I want to restrict duplicate usernames in a table.
The only way I could think was to run a select query and then if that doesn't return anything run the insert query. For some reason though I cant get it to work...
My db select Function
function getAllUsers($user)
{
$stmt = $this->db->stmt_init();
$stmt->prepare('SELECT username from users where username=? ');
$stmt->bind_param("s", $user);
$stmt->bind_result($username);
$stmt->execute();
$results = array();
while($stmt->fetch())
{
$results[] = array('username' => $username);
}
$stmt->close();
return $results;
}
My php code (this is in a different page)
foreach ($GLOBALS['db']->getAllUsers($_POST['username']) as $i)
{
$results = "".$i['username']."";
break;
}
if(strcmp($results, "")==0)
{
if($GLOBALS['db']->addUser($_POST['username'],$_POST['password']))
{
session_destroy();
echo "registerSucces";
}
else
{
session_destroy();
echo "registerError";
}
}
else
{
echo "userNameExists";
}
Can you see whats wrong with this???
Thanks
Mike
Still cant find how to make the above code work but just in case someone needs this: A temporary simple solution is not to compare strings at all and instead have a counter in the foreach loop and then check that upon a desired number(0 in my case)...
SQLite supports the UNIQUE constraint. Simply declare a UNIQUE index on the column and check whether an INSERT fails.
If you're using the username as the primary key in your tables, you can use the INSERT OR IGNORE command instead of checking to see if the username already exists.
If SQLite finds that an INSERT OR IGNORE command will conflict with an existing row in your table, it will simply ignore the command.
You can find out more stuff in the SQLite documentation for the INSERT command