MySQL Database table from PHP code [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have attempted to create a mysql query to create the database schema but with no success, here is the php code that get data from the database, could you please help me create a mysql script that will create the database tables?
here is the php script:
foreach($string["statuses"] as $status) {
$selectSQL = 'SELECT * FROM twitter WHERE t_id="'.$status["id"].'" ';
$queryset = '';
$queryset = $mysqli->query ($selectSQL);
if(mysqli_num_rows($queryset)==0)
{
$text = mysqli_real_escape_string($mysqli, $status["text"]);
$loc = mysqli_real_escape_string($mysqli, $status["user"]["location"]);
$user_id = mysqli_real_escape_string($mysqli, $status["user"]["id"]);
$app = mysqli_real_escape_string($mysqli, $status["source"]);
$img = mysqli_real_escape_string($mysqli, $status["user"]["profile_image_url"]);
$retweet = mysqli_real_escape_string($mysqli, $status["retweet_count"]);
$favorite = mysqli_real_escape_string($mysqli, $status["favorite_count"]);
$mysqli->query('INSERT INTO `twitter` VALUES (NULL,"'.$status['id'].'","'.$text.'","'.$status['created_at'].'","'.$loc.'","'.$user_id.'","'.$app.'","'.$img.'","'.$retweet.'","'.$favorite.'")');
}
}

First, some nomenclature;
This:
$mysqli->query('INSERT INTO twitter VALUES (NULL,"'.$status['id'].'","'.$text.'","'.$status['created_at'].'","'.$loc.'","'.$user_id.'","'.$app.'","'.$img.'","'.$retweet.'","'.$favorite.'")');
is a command to place data into a table that already EXISTS, unless you want a table of PHP MySQL query strings, which I'm thinking you do not.
In either case, you will need to read up on the CREATE TABLE section of MySQL, and learn how to create a table in MySQL. Your question is unclear, and no one will just do the work for you here. Stack Overflow is a learning place.
If you want to have an elephant circus, you'll need to know about elephants...or hire an elephant trainer.
Once you understand how to create the table, you can learn how to read (query) it, insert into it (as this query does), remove entries, alter the table structures, and more. This will require some PHP knowledge, unless you choose another scripting language, like Ruby or Perl, and you'll want to have a pleasant database manager to view your db; my personal favorite is Adminer, available at
http://adminer.org
There are others, which you can Google easily. Good luck with your work.

Check out this link.
https://www.w3schools.com/php/php_mysql_create_table.asp
You have to write the SQL yourself though.

Related

Can I use an if on foreach in such a case? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a little problem, am trying to read values from mysql table. I have done research and could not find a definite or conclusive answer on this. I will describe the problem:
select data from mysql table using a where e.g where gender=female.
count the results and return the count - just to help know how many records were found
compare a value in table, e.g 'taken' and 'available',
if 'taken' = 'available' in the first record, go to next record(and compare again), if not perform a specific operation in this case can be update or insert or anything of that sort.
the first three are ok and the only problem is, part 4. Kindly help. This is a php problem. Looking forward for your help.
As was said, if you're merely going to skip the record then you may as well not retrieve them in the first place (and thus incur the overhead for having to extract them into PHP memory, etc):
SELECT * FROM `your_table` WHERE `gender` = 'female' AND `taken` = `available`;
However, if you have a specific reason to do this, you can merely do the following:
foreach ($hotels as $hotel) {
// skip if the item is not available, logic can be changed if necessary
if ($hotel->taken >= $hotel->available) continue;
// do the other work here...
}
I interpreted your conditions a little here, assuming you wanted to skip people who aren't 'available'. Though it does look like you wanted the opposite, in which case you can switch the logic in the sql from != to = and in php from != to ==.
Updated: To reflect additional comments made.
Create connection to your database using mysqli or by using PDO.
$db = new PDO($mysqlhost,$username,$password);
$statement = $db->prepare($sqlstatement);
$rows = $statement->execute();
foreach($rows->fetch() as $row)
{
if($row['column_name']==something)
{
//do work
}
else
{
//do work
}
}

how to check if a record exist in a database before inserting with php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a form that collects data and sends to a database using php, with a code snippet i got online.
$con=mysqli_connect("localhost","root","famakin","k");
if(mysqli_connect_errno())
{
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
$sql="INSERT INTO transactions(Username,Insured_Name,combined,Residential_Address,Telephone,Email,Make_Of_Car,Model,Engine_Number,Year_Of_Manufacture,Chassis_Number,Vehicle_Class,Colour,Registeration_Number,Product_Type,Premium,Policy_Number,Start_Date,Expiry_Date,Date_Begin,Type_Of_Insurance,Status, Transaction_id)VALUES('$_POST[Username]','$_POST[Insured_Name]','$_POST[combined]','$_POST[Residential_Address]','$_POST[Telephone]','$_POST[Email]','$_POST[Make_Of_Car]','$_POST[Model]','$_POST[Engine_Number]','$_POST[Year_Of_Manufacture]','$_POST[Chassis_Number]','$_POST[Vehicle_Class]','$_POST[Colour]','$_POST[Registeration_Number]','$_POST[Product_Type]','$_POST[Premium]','$_POST[Policy_Number]','$_POST[Date]','$_POST[Date_Expiry]','$_POST[Date_Begin]','$_POST[Type_Of_Insurance]','$_POST[Status]','$_POST[Transaction_id]')";
if(!mysqli_query($con,$sql))
{
die('Error:'.mysqli_error($con));
}
mysqli_close($con);
This works for inserting details into the database,but i want to check if for example the username in which i am inserting into the database exists,please how do i go about this with what i have already?
regards
There are two main approaches, essentially...
SELECT from the database before trying to INSERT. If the record is found by the SELECT, don't perform the INSERT and instead respond to the user accordingly.
Place a UNIQUE constraint on the column (or set of columns) which needs to be unique in the table. This would cause the INSERT to fail, and the code would have to catch and handle that failure and respond to the user accordingly.
The second option puts the responsibility squarely on the database itself, which is important if anything else if ever going to use that database and needs to maintain that same responsibility.
Also, and this is important, please note that your code is open to SQL injection attacks, which allows users to execute their own code on your server. You'll want to read up on that so you can protect your application.
Here, you can do it via mysqli_num_rows():
$username = mysqli_real_escape_string($con, $_POST['Username']);
$check_select = mysqli_query("SELECT * FROM `transactions` WHERE Username = '$username'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
else{
// do something else
}
Although there are other ways to do this, it is but one example.
You can avoid this by also setting your column(s) as UNIQUE.
By the way, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they much safer.
Just do a SELECT query before the INSERT. If a record with that username exists then don't insert the record.
Well before you insert one you want to query for it's existence (please refer to Google on how to "Select data from Database PHP").
If that select count(*) from Transactions.... where Username =.. returns something other than 0 the username is already taken.
Note: I have bigger concerns about the fact you include POST-Parameters directly into your SQL-Query string and recommend you read something about "SQL Injection PHP".

Pdo update with variables inside the query [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Ok so i store the column i want to update in side a variable so i need to put the variable in side the main query i try and do it like so
$sqlltyryrt = "UPDATE user_items SET :fggdgdf = :fggdgdf +1 WHERE username=?";
$qqqqq = $db->prepare($sqlltyryrt);
$qqqqq->execute(array('fggdgdf'=>$fggdgdf),$_SESSION['username']);
I have searched for an answer and have found a thread here on the site doing the same:
Using a passed variable in a query using PDO (Oct 2011; by Don S)
$sqlltyryrt = "UPDATE user_items SET :fggdgdf = :fggdgdf +1 WHERE username=?";
$qqqqq = $db->prepare($sqlltyryrt);
$qqqqq->execute(array('fggdgdf'=>$fggdgdf),$_SESSION['username']);
You can't bind the names of columns; so that isn't going to work. There's no way to use a bound variable for a column or table name, so the only way to do this is to actually interpolate the variables into the string:
$sqlltyryrt = "UPDATE user_items SET $fggdgdf = $fggdgdf +1 WHERE username=?";
$qqqqq = $db->prepare($sqlltyryrt);
$qqqqq->execute(array($_SESSION['username']));
But you need to be very sure that you've sanitized the variables, else you're open to SQL injection. You can use whitelisting for this, as you should be able to generate an array of possible column names and can check that the variables are present in that array.
But the fact that you're trying to bind the names of comments implies that your database design could do with looking at.

PHP to input email to database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
This is the site that I am trying to create the script for http://facechat.louisdickinson.com/
The idea is people can save there email to my database, and another button called "Start Call" will randomly select a email and call it using:
facetime://email#email.com
Effectively this will create a "omegle" style web-based facetime chat site.
I am new to MySQL and PHP and don't know where to start, any help will be appreciated!
I don't know, what kind of help do you need.. First of all, you should have a php script, witch can take the posted name/e-mail pair.
In this script, you should sanitize the posted values, than you can add it to your database with the following:
$query = "INSERT INTO <tableName> (`name`, `e-mail`) VALUES ( '".$postedName."', '".$postedMail."' )";
On button press, you should have another php script, for selecting the random e-mail:
$query = "SELECT COUNT(*) FROM <tableName>";
$max should be the query result.
$random = rand( 0 , $max - 1 );
$query = "SELECT `e-mail` FROM <tableName>" LIMIT $random, 1";
With this query you got a random e-mail.
Do you need more exact code? Please be more exact on what you need!
Kind regards,
hotzu
In php:
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_selectdb("database"); // '' for an auto increment column
mysql_query("INSERT INTO TABLE VALUES ('$email', ''));
And for more info http://www.w3schools.com/php/php_mysql_intro.asp

How to add entries to mysql db using API..? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to PHP and mysql and i am trying to make API's for my iphone app.
So far i have been able to connect and retrive data from my sql database now m trying to make entries to it using API's and parameters.
Can anyone help me out here please.
Thanks alot!!
If by to make entries you mean adding data to the database.
You do this in the same way that you select data.
Instead of issuing a select statement like:
SELECT x,y,z FROM table1
You do:
INSERT INTO table1 (x,y,z) VALUES ('a', 1, 'test')
Or:
UPDATE table1 SET x = 'b' WHERE x = 'a'
How you pass parameters depends on the API you use.
It is best (safest) to use PDO to pass parameters.
How to get parameters out of a url
In order to get the parameters out of the url (e.g.: example.com/test.php?username=xyz&password=!##$%) do:
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$query = "SELECT * FROM users WHERE username = '$username'
AND passhash = sha2(CONCAT(salt,'$password'),512)";
Note that it's vital to put single quotes around the injected variable names when using mysql_real_escape_string() or the escaping will be useless. Used like this the code is 100% secure from SQL-injection.
If you're using PDO, you can drop the mysql_real_escape_string() if not you need it to prevent SQL-injection.
Links
http://dev.mysql.com/doc/refman/5.5/en/update.html
http://dev.mysql.com/doc/refman/5.5/en/insert.html
http://php.net/manual/en/ref.pdo-mysql.php
https://stackoverflow.com/search?q=%5Bphp%5D+%5Bmysql%5D+pdo
http://php.net/manual/en/reserved.variables.get.php
http://php.net/manual/en/function.mysql-real-escape-string.php

Categories