how to get columns in a table in mysql with php? - php

I create a table in my database using this code
$con = mysqli_connect($host,$username,$password,$db);
$sql = "CREATE TABLE My_Table(";
for($i = 1; $i<=50 ; $i++) {
if($i!=50)
$sql .= "id_".$i." INT(30) NOT NULL DEFAULT '0',";
else
$sql .= "id_".$i." INT(30) NOT NULL DEFAULT '0')";
}
if (mysqli_query($con,$sql)) {
echo "Done";
}
Now I have $var = 10; and I want to get for example id_10 and change the value of id_10 to id_10+=$var.
I'm a beginner in PHP/MySQL. Thanks in advance.

select:
my $stmt = $con->prepare($con,"SELECT id_".$var." FROM My_table WHERE ...");
$stmt->bind_param($stmt, /* something here which depends on what you need for your condition */ );
$stmt->execute();
update:
my $stmt = $con->prepare($con,"UPDATE My_table SET id_".$var."=id_".$var."+? FROM My_table WHERE ...");
$stmt->bind_param($stmt,"i",$var /* to be changed depending on condition */);
$stmt->execute();
Note that you must make sure that $i is very strictly checked if it comes from the browser ($_GET, $_POST, $_COOKIE...). Otherwise that opens the door to horrible SQL injection errors.
But note my comment above, I don't think this is a good schema.

Related

Hard coded to Dynamic values

I have been given a task to convert the hardcoded fields into dynamic fields.I have changed it partially to dynamic
Let me explain you the situation ,
We have a lot of databases and each database has a table by name Surveys
By using the DESCRIBE statement we will retrieve the fields in the Surveys table regardless of the database .
I need to know the way where we can loop again and again till all the fields in the survey table appears.
In the below code I have left the for loop blank .
Please let me know the changes that neeeds to be done to get this working
I would really appreciate any kind of help
function insertIntoUserUploadFileds() {
$describe="DESCRIBE surveys";
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
$inUse="0";
$type="";
//for(){
if($field=='type'){
$type="N";
}elseif(($field=='fname') || ($field=='lname') || ($field=='phone')){
$inUse="1";
$type="T";
}elseif($field=='email'){
$inUse="1";
$type="E";
}
//$sql .= "('".$field."', '".$inUse."', '0', '
$result1 = mysql_query ($describe);
$result = mysql_query ($sql);
//}
}
$result1 = mysql_query ('DESCRIBE surveys');
//here is how you retieve all field and check
while($row = mysql_fetch_array($result1)) {
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
//here you can do if else to check the column name
if($row['field']=='type')
{
$type="N";
}
else if(($row['field']=='fname') || ($row['field']=='lname') || ($row['type']=='phone'))
{
$inUse="1";
$type="T";
}
else ($row['field']=='email')
{
$inUse="1"
$type="E";
}
//build your query
$sql .= "('".$field."', '".$inUse."', '0', '......)
//execute your complete query
$result = mysql_query ($sql);
}//end of while
Instead of using DESCRIBE, if you are trying to retrieve the default type of a particular column you might look into this. It describes how to break down the information from a particular table. Codex

mysql_query(INSERT ...) function not working in my code

I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.

mysqli returns true for INSERT query, row not inserted

if ($word != '' && $text != '') {
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($source = $result->fetch_assoc()) {
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
if ($result = $conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"))
echo 1;
}
}
The above is the INSERT code (and update) the UPDATE code works fine, however when the INSERT query is called the query returns true but when i check the data, it hasn't been inserted.
Any help is appreciated, thanks in advance.
EDIT:
variables table structure:
`word` varchar(100) NOT NULL, //also PRIMARY KEY
`text` text NOT NULL
You have a single = in an if condition.
maybe you wanted:
if ($result->num_rows){ // see if there are any rows
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
tested:
$conn = new mysqli('localhost', 'root', '', 'test');
$word = 'word1';
$text = 'text1';
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($result->num_rows){
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
I've been struggling with the same problem but solved it in a different way.
Check how many rows are affected, like this (this example uses mysqli but I hope you'll get the point):
$number_of_rows_affected = mysqli_affected_rows($conn);
If $number_of_rows_affected = 0 then INSERT wasn't working. A number larger than 0 means a successful INSERT.
Not sure why you use backticks around 'word' and 'text' in your query.
For debugging this, I write the query to a string and print it before executing it, to make sure the query is what I wanted, so use:
$query = "INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"
print("$query")
if ($result = $conn->query($query))
echo 1;
Are you sure the insert does not work? Do you close your database connection before you check, maybe the results have just not been committed to your database when you check?

Can I do multiple update SQL with php?

I want to edit a table from my database.That table have many data.
I will show sample.Do I need to write many mysql update statement?Have other method to write a only one statement? I am beginner for php? Thank all my friend.Sorry for my english.
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle2',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext2',
WHERE `id` ='$id2';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle3',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext3',
WHERE `id` ='$id3';");
etc.............
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle30',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext30',
WHERE `id` ='$id30';");
You want to update multiple rows from one table with specific data, so bad news you have to do it one by one.... but you can improve your code. If I where you I will create a function and I just call it, something like
function update_my_data($movilefilltex1,$id1){
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
.......
}
So to make the multiple insert you can call update_my_data(value1,valu2) the times that you need. for example in a loop or just whenever you need it.
If there is a UNIQUE index on id (and there will be if it's your PRIMARY KEY), you could use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext) VALUES
('$id1', '$mobiletitle1', 1, '$mobilefulltext1'),
('$id2', '$mobiletitle2', 1, '$mobilefulltext2'),
-- etc.
ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext);
Note that this will, of course, insert new records if they don't already exist; whereas your multiple-UPDATE command approach will not (it would raise an error instead).
In either case, you could build/execute the SQL dynamically from within a loop in PHP.
I would also caution that you would be well advised to consider passing your variables to MySQL as parameters to a prepared statement, especially if the content of those variables is outside of your control (as you might be vulnerable to SQL injection). If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Putting it all together (using PDO instead of the deprecated MySQL extension that you were using):
for ($i = 1; $i <= 30; $i++) {
$sqls[] = '(?, ?, 1, ?)';
$arr[] = ${"id$i"};
$arr[] = ${"mobiletitle$i"};
$arr[] = ${"mobilefulltext$i"};
}
$sql = 'INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext)
VALUES
' . implode(',', $sqls)
. 'ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext)';
$db = new PDO("mysql:dbname=$db", $user, $password);
$qry = $db->prepare($sql);
$qry->execute($arr);
Note that you might also consider storing your 1..30 variables in arrays.
update table1,table2 SET table1.column1 = 'valueX',table2.coulumn2 = 'valueX' where table1.column = table2.coulumn2 ;

Issues incrementing a field in MySQL/PHP with prepared statements

I have the following code which is supposed to increment a field value by 1 in a prepared PHP mysql statement:
function db_OP_doVote($pdo, $postid, $votetype)
{
$prepStatement = $pdo->prepare(
"UPDATE content_posts SET `:votetype` = `:votetype` + 1 WHERE `id` = :id"
);
$prepStatement->execute(array(':votetype' => $votetype, ':id' => $postid));
echo "Success";
}
This however, does nothing. No error is thrown back about incorrect SQL syntax and the script runs to completion, but my field does not update at all.
The values for this script are fed through a jQuery post() to this script:
//isset checking here
$postID = (int)$_POST['id'];
$voteType = $_POST['type'];
if ($voteType == "y")
{
$trueType = "v-cool";
}
elseif ($voteType == "m")
{
$trueType = "v-meh";
}
elseif ($voteType == "n")
{
$trueType = "v-shit";
}
else
{
die();
}
$db = db_Connect();
db_OP_doVote($db, $postID, $trueType);
Which also appears to filter the values and send them fine. I can't wrap my head around what the issue could be. The field being incremented is a BIGINT(20).
What am I missing?
EDIT: Solved the issue.
N.B's comment hit the nail on the head - binding the column name causes it to be quoted, which invalidates the query. Thanks!
you can't use binding for the field names.
from the question it seems that your setup is wrong.
you should have another table with votes and vote types as data.
You can't parameterize column names with PDO. What you can do is have hard-coded values (which you basically already have) and construct the SQL string accordingly. I would check this value in the actual function too though, just to be on the safe side:
function db_OP_doVote($pdo, $postid, $votetype)
{
if( !in_array( $votetype, array( 'v-cool', 'v-meh', 'v-shit' /*, etc. */ ), true ) )
{
throw new InvalidArgumentException( 'Unexpected $votetype: ' . $votetype );
// or simply return false perhaps
}
$sql = '
UPDATE content_posts
SET `' . $votetype . '` = `' . $votetype . '` + 1
WHERE `id` = :id
';
$prepStatement = $pdo->prepare( $sql );
$prepStatement->execute(array(':id' => $postid));
echo "Success";
}
However, this strategy suggests your database design could use a little more attention. The way you have it now, is that for every type of vote, you have a column. This is not really efficient and/or flexible database design. What happens if you get asked to add another type of vote?
I'd suggest adding another table, to be more flexible:
CREATE TABLE `content_post_vote` (
`content_post_id` int(11) NOT NULL,
`vote_type` enum('cool','meh','shit') NOT NULL, # using enum() to assure valid vote types
`votes` bigint(20) DEFAULT NULL,
PRIMARY KEY (`content_post_id`,`vote_type`)
)
Then your query would be something like:
$sql = '
INSERT INTO `content_post_vote` (`content_post_id`,`vote_type`,`votes`)
VALUES( :id, :votetype, 1 )
ON DUPLICATE KEY UPDATE `votes` = `votes` + 1
';
What this does is insert a vote if there is no record for a certain primary key (content_post_id,vote_type) yet, and else update the record with a vote if the record already exists.
Then to query the database for how many votes of a particular type a particular content_post has gotten, you do this:
$sql = '
SELECT `votes` # or perhaps more columns
FROM `content_post_vote`
WHERE `content_post_id` = :id AND
`vote_type` = :votetype
';

Categories